1 / 33

ADO.NET

ADO.NET. 부산 IT 직업전문학교 성 명 건. 목차. about ADO.NET 데이터베이스 연결 데이터베이스 조작 데이터 가져오기 DataTable, DataColumn, DataRow 클래스 DataView 클래스 DataSet 클래스 DataAdapter 클래스. 2. 학습목표. ADO.NET 을 쓰는 이유를 배우고 , 이전의 ADO 와의 차이점을 안다 데이터베이스 연결하는 방법을 배운다 Command 클래스에 대해서 학습한다

ciara-wong
Download Presentation

ADO.NET

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ADO.NET 부산IT직업전문학교 성 명 건

  2. 목차 • about ADO.NET • 데이터베이스 연결 • 데이터베이스 조작 • 데이터 가져오기 • DataTable, DataColumn, DataRow 클래스 • DataView 클래스 • DataSet 클래스 • DataAdapter 클래스 2

  3. 학습목표 • ADO.NET을 쓰는 이유를 배우고, 이전의 ADO와의 차이점을 안다 • 데이터베이스 연결하는 방법을 배운다 • Command 클래스에 대해서 학습한다 • Adapter와 DataSet클래스를 통해 비연결 지향 방법 연결에 대해서 배운다 • Reader클래스로 연결지향 방법에 대해 배운다 • ADO.NET을 통해 데이터베이스 조작 예제를 학습한다

  4. about ADO.NET DataAdpter DataSet WinForm WebForm Connection Command Other DB DataReader Data Consumers Data Provider 4

  5. about ADO.NET 5

  6. 관련 네임스페이스 • ADO.NET • Data Provider • OleDB Vs. MSSQL 6

  7. 데이터베이스 연결 • 순서 • Connection 객체 생성 • 데이터베이스 연결 문자열 지정(DSN) • Connection 객체의 Open메서드로 데이터베이스 연결 • Connection 객체의 Close메서드로 데이터베이스 연결 해제 7

  8. 데이터베이스 연결 • ConnectionString SqlConnection conn = new SqlConnection(); conn.ConnectionString = “Server =localhost;database=Northwind;UID=sa;PWD=;” ; conn.ConnectionString = “Server=localhost;database=Northwind;UID=sa;PWD=;” ; conn.ConnectionString = “Addr=127.0.0.1;database=Northwind;UID=sa;PWD=;” ; conn.ConnectionString = “Data Source=127.0.0.1;database=Northwind;UID=sa;PWD=;” ;

  9. 데이터베이스 연결 • Connection 클래스 멤버 메서드 9

  10. 데이터베이스 연결 • MS-SQL 연결 using System.Data; using System.Data.SqlClient; // OleDb class ConsoleConnection { static void Main(string[] args) { SqlConnection conn = new SqlConnection(); // OleDbConnection conn.ConnectionString = "Server=localhost;database=ADO;uid=sa;pwd=;" ; //conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\ado.mdb“; try { conn.Open(); Console.WriteLine("데이터베이스 연결 성공.."); } catch(Exception ex) { Console.WriteLine("데이터베이스 연결 실패.."); } finally { if(conn != null) { conn.Close(); Console.WriteLine("데이터베이스 연결 해제.. "); } } } } 명명된 파이프와 TCP/IP 확인

  11. 데이터베이스 조작 • 순서 • 데이터베이스 연결 : Connection 객체 생성 • 명령 수행 준비 : Command 객체 생성 • 속성 지정 : Command 객체의 CommandText 속성 지정(쿼리, 저장프로시저, 테이블) • SQL 쿼리문 실행 : Execute() 메서드로 쿼리문 실행 • Command 클래스 생성자 public SqlCommand(); public SqlCommand(string commandText); public SqlCommand(string commandText, SqlConnection connection); public SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction);

  12. 데이터베이스 조작 Command 클래스 속성 12

  13. 데이터베이스 조작 • Command 클래스 멤버 메서드

  14. 데이터베이스 조작 • CommandText SqlCommand cmd = new SqlCommand(); cmd.CommandText = “SELECT * FROM Employees WHERE LastName = ‘King’”; //cmd.CommandText = “SELECT * FROM Employees WHERE LastName = ‘@LastName’”; cmd.CommandType = CommandType.Text; cmd.Connection = conn;

  15. 데이터 가져오기 • DataReader 클래스 생성자 • DataReader 클래스 속성 SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(“SELECT * FROM Employees”, conn); SqlDataReader read = cmd.ExecuteReader();

  16. 데이터베이스 조작 • CreateParameter SqlCommand cmd = new SqlCommand(); … 1) SqlParameter param = cmd.CreateParameter(); // 파라미터 생성 param.ParameterName = “@LastName”; // 파라미터 이름 지정 param.SqlDbType = SqlDbType.NVarchar; // 파라미터 타입형 param.Size = 20; // 타입형의 사이즈 Varchar(10) param.Value = “King”; // 들어가는 값 2) cmd.Parameters.Add(“@LastName”, SqlDbTypeNVarchar, 20).Value = “King”; // 권장권장

  17. 데이터 가져오기 • FieldCount • RecordsAffected SqlCommand cmd = new SqlCommand(“SELECT * FROM Employees”, conn); SqlDataReader read = cmd.ExecuteReader(); Console.WriteLine(“Employees 의 전체 컬럼 개수 : {0}”, read.FieldCount); SqlCommand cmd = new SqlCommand(“Update Employees SET Country = ‘USA’ WHERE EmployeeID = 9”, conn); SqlDataReader read = cmd.ExecuteReader(); Console.WriteLine(“Employees의 변경된 레코드개수 : {0}”, read.RecordsAffected);

  18. 데이터 가져오기 • Item SqlCommand cmd = new SqlCommand(“SELECT * FROM Employees”, conn); SqlDataReader read = cmd.ExecuteReader(); while (read.Read()) { Console.WriteLine(read[“EmployeeID”] + “\t” + read[“LastName”] + “ “ + read[“FirstName”]); // 권장 Console.WriteLine(read[0] + “\t” + read[1] + “ “ + reate[2]); // 권장하지 않음 }

  19. 데이터 가져오기 DataReader 클래스 멤버 메서드 19

  20. DataTable, DataColumn, DataRow 클래스 • 클래스 • DataColumn // User 컬럼을 만들고 Type을 System.String형으로 지정할 경우 DataColumn col = new DataColumn(“User”, Type.GetType(“System.String”));

  21. DataTable, DataColumn, DataRow 클래스 • DataColumn // User 컬럼을 만들고 Type을 System.String형으로 지정할 경우 DataColumn col = new DataColumn(); col.DataType = Type.GetType(“System.String”); col.Caption = “데이터컬럼”; col.ColumnName = “User”; col.AllowDBNull = false; col.ReadOnly = true; col.Unique = true; // 컬럼 Num이며 Primary Key 속성과 자동증가 속성을 가지는 컬럼 DataColumn col = new DataColumn(); col.ColumnName = “Num”; col.AutoIncrement = true; col.AutoIncrementSeed = 100; // 자동 증가 초기값 100 으로 col.AutoIncrementStep = 10; // 자동 증가 값 10

  22. DataTable, DataColumn, DataRow 클래스 • DataRow 클래스 생성자 • DataRow 클래스 속성 DataRow row = DataTable.NewRow();

  23. DataTable, DataColumn, DataRow 클래스 • DataRowState 열거형

  24. DataTable, DataColumn, DataRow 클래스 • DataTable 클래스 • 메모리 내에 존재하는 테이블 • 테이블 정보를 DataAdapter나 DataSet 클래스를 참고해 작성 • DataTable 클래스 생성자 • DataTable 클래스 속성 / 메서드 • http://msdn.microsoft.com/ko-kr/library/system.data.datatable_properties(VS.80).aspx DataTable table = new DataTable(“Member”);

  25. DataTable, DataColumn, DataRow 클래스 DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("Key"), new DataColumn("Index"), new DataColumn("Value")}); dt.Rows.Add(1, 10, "홍길동"); dt.Rows.Add(2, 20, "박길동"); dt.Rows.Add(3, 30, "김길동"); dt.PrimaryKey = new DataColumn[] { dt.Columns["Index"] }; //1. 일반검색 DataRow[] rows = dt.Select("Key=" + 2); Console.WriteLine(rows[0]["Value"].ToString()); //2. 키로검색 DataRow row = dt.Rows.Find(30); Console.WriteLine(row["Value"].ToString()); //3. Index 로검색 DataRow row2 = dt.Rows[0]; Console.WriteLine(row2["Value"].ToString());

  26. DataView 클래스 • 임시 테이블 • 필요한 경우 메모리에 생성 • 복잡한 쿼리문을 단순화 시켜 개발 가능 • DB에서의 View 기능을 DataView 클래스를 통해 구현 • DataView는 DataTable로 부터 특정 필드와 레코드 정보를 가져오고, GridView 같은 Data Binding 컨트롤에 출력 • DataView 클래스 생성자 public DataView DataView(DataTable tbl);

  27. DataTable, DataColumn, DataRow 클래스 • DataTable & DataView 예제

  28. DataSet 클래스 • 비연결 지향 • DataSet = 메모리 DataBase • DataSet을 통해 실제 DB의 종류에 상관없이 DataAdapter 객체를 통해 메모리상의 해당자료(테이블, 컬럼, 레코드정보)를 저장 가능 • DB에 하나 이상의 Table이 있듯이, DataSet은 하나 이상의 DataTable 개체 소유 • DataRelation을 이용한 Table간의 관계설정 DataSet data = new DataSet(); DataColumn col_Parents= data.Tables[0].Columns[0]; DataColumn col_Child = data.Tables[1].Columns[0]; DataRelation relation = new DataRelation(“Relation”, col_Parents, col_Child); data.Relation.Add(relation);

  29. 쿼리문을 통해 읽어오는 data는 주로 DataReader사용 비 연결지향(DataSet)을 사용할 때 DataAdapter/DataSet을 사용하면 초기 Data 로딩은 느린편 DB에서 읽어오는 시간은 상대적으로 빠름 DB와의 연결상태 유지로 인해 시스템자원 낭비 필요한 경우에만 DB와 연결됨으로 인해 시스템 자원 낭비 최소화 DataAdapter 클래스 • DB에서 데이터 가져와 DataSet의 DataTable 생성후 레코드 추가 • ADO.NET DB 연결방법 두가지 • DataReader 와 DataAdapter

  30. DataAdapter 클래스 • DataAdapter 클래스 생성자 public SqlDataAdapter(); public SqlDataAdapter(SqlCommand selectCommand); public SqlDataAdapter(string selectCommandText, SqlConnection selectConnection); public SqlDataAdapter(string selectCommandText, string selectConnectionString);

  31. DataAdapter 클래스 • DeleteCommand 속성 • DataAdapter 클래스 멤버 메서드 string sql = “SELECT * FROM Emplyoees”; SqlConnection conn = new SqlConnection(“Server=localhost;DataBase=Northwind;uid=sa;pwd=;”); SqlDataAdapter adapter = new SqlDataAdapter(sql, conn); adapter.DeleteCommand = new SqlCommand(“DELETE FROM Employees WHERE EmployeeID = 10”, conn);

  32. DataAdapter 클래스 • DataAdapter, DataSet 예제

  33. 학습정리 • ADO.NET이 이전 방식인 ADO보다 좋은 점은 무엇인가? • OleDB에서 사용할 연결 개체는 무엇인가? • Command 클래스에 ExecuteReader() 메서드는 어디에서 많이 쓰는가? • Read 클래스에 데이터가 있는 지 확인하는 방법은? • Adapter와 DataSet을 이용하여 윈폼 예제를 작성할 수 있는가?

More Related