C Programming Version 2 0 ADO NET MCSD

  • Slides: 30
Download presentation
C# Programming Version 2. 0 ADO. NET 김규태 (MCSD. Net, MCSE, MCDBA, SCJP)

C# Programming Version 2. 0 ADO. NET 김규태 (MCSD. Net, MCSE, MCDBA, SCJP)

학습목표 1. ADO. NET 개요 2. ADO. NET 관련 네임스페이스 3. Data Provider 4.

학습목표 1. ADO. NET 개요 2. ADO. NET 관련 네임스페이스 3. Data Provider 4. Data. Base 연결(Connection) 5. Data. Base 조작(Command) 6. Data 가져오기 (Data. Reader) 7. Data. Table, Data. Column, Data. Row Class 8. Dava. View Class 9. Data. Set Class 10. Data. Adapter Class

1. ADO. NET 개요 (1/2) Data. Adpter Data. Set Win. Form Web. Form Connection

1. ADO. NET 개요 (1/2) Data. Adpter Data. Set Win. Form Web. Form Connection Command Other DB Data. Reader Data Provider Data Consumers

1. ADO. NET 개요 (2/2) ADO. NET 아키텍처

1. ADO. NET 개요 (2/2) ADO. NET 아키텍처

2. ADO. NET 관련 네임스페이스 포함하고 있는 클래스 System. Data 데이터 관련 클래스 (ADO.

2. ADO. NET 관련 네임스페이스 포함하고 있는 클래스 System. Data 데이터 관련 클래스 (ADO. NET 필수클래스) System. Data. Common System. Data. Ole. Db 데이터 공유 클래스 (Data Provider간에 공유되는 타입) Ole. Db 제공 클래스 System. Data. Sql. Client MSSQL 서버 제공 클래스 System. Data. Sql. Types MSSQL 서버 기본 데이터 형식 클래스 3. Data Provider 역할 Ole. DB SQL 데이터베이스 연결 Ole. Db. Connection Sql. Connection SQL명령수행 Ole. Db. Command Sql. Command 데이터 읽어오기 Ole. Db. Data. Reader Sql. Data. Reader 데이터 전송 Ole. Db. Data. Adapter Sql. Data. Adaper

4. 데이터베이스 연결(Connection) 2/5 Connection. String Sql. Connection conn = Sql. Connection(); conn. Connection.

4. 데이터베이스 연결(Connection) 2/5 Connection. String Sql. Connection conn = Sql. Connection(); conn. Connection. String = “Server =localhost; database=PUBS; UID=sa; PWD=; ” ; conn. Connection. String = “Addr=127. 0. 0. 1; Initial. Catalog=PUBS; uid=sa; pwd=; “ ; conn. Connection. String = “data. Source=127. 0. 0. 1; database=PUBS; uid=sa; pwd=; ” ; Connection. Timeout - 연결할 동안 기다리는 시간(기본값은 15초) - 0으로 설정하면 연결시도를 무기한 대기

4. 데이터베이스 연결(Connection) 3/5 Connection 클래스 멤버 메소드 메서드 Change. Database 설명 Close 열려있는

4. 데이터베이스 연결(Connection) 3/5 Connection 클래스 멤버 메소드 메서드 Change. Database 설명 Close 열려있는 Sql. Connection에 대해 현재 DB를 변 경 DB 연결 종료 Create. Command Sql. Command 개체 생성 Open DB 연결 Dispose Sql. Connection 리소스 해제

4. 데이터베이스 연결(Connection) 4/5 ex) MS-SQL 연결 using System; using System. Data. Sql. Client;

4. 데이터베이스 연결(Connection) 4/5 ex) MS-SQL 연결 using System; using System. Data. Sql. Client; class Console. Connection { static void Main(string[] args) { Sql. Connection conn = new Sql. Connection(); conn. Connection. String = "Server=localhost; database=ADO; uid=sa; pwd=; " ; try { conn. Open(); Console. Write. Line("데이터베이스 연결 성공. . "); } catch(Exception ex) { Console. Write. Line("데이터베이스 연결 실패. . "); } finally { if(conn != null) { conn. Close(); Console. Write. Line("데이터베이스 연결 해제. . "); } }

4. 데이터베이스 연결(Connection) 5/5 ex) OLE DB 연결 using System; using System. Data. Ole.

4. 데이터베이스 연결(Connection) 5/5 ex) OLE DB 연결 using System; using System. Data. Ole. Db; class Console. Connection 2 { static void Main(string[] args) { string source = @"Provider=Microsoft. Jet. OLEDB. 4. 0; Data Source=c: ado. mdb" ; Ole. Db. Connection conn = new Ole. Db. Connection(source); try { conn. Open(); Console. Write. Line("데이터베이스 연결 성공. . . "); } catch(Exception ex) { Console. Write. Line("데이터베이스 연결 실패. . . "); } finally { if(conn != null) { conn. Close(); Console. Write. Line("데이터베이스 연결 해제. . . "); } }

5. 데이터베이스 조작(Command) 1/5 ① 데이터베이스연결 : Connection 객체생성 ② 명령 수행 준비 :

5. 데이터베이스 조작(Command) 1/5 ① 데이터베이스연결 : Connection 객체생성 ② 명령 수행 준비 : Command 객체 생성 ③ 속성지정 : Command객체의 Command. Text 속성지정 (쿼리, 저장프로시저, 테이블) ④ SQL쿼리문 실행 : Execute() 를 통해 쿼리문 실행 Command 클래스 생성자 public Sql. Command(); public Sql. Command(string command. Text, Sql. Connection connection); public Sql. Command(string command. Text, Sql. Connection connection, Sql. Transaction transaction );

5. 데이터베이스 조작(Command) 3/5 Command. Text Sql. Command cmd = new Sql. Command(); cmd.

5. 데이터베이스 조작(Command) 3/5 Command. Text Sql. Command cmd = new Sql. Command(); cmd. Command. Text = “select * from member where user =“david”; cmd. Command. Type = Command. Type. Text; Command. Type (Text; Strore. Procedure; Table. Direct) Ole. DB전용 cmd. Command. Text = “member”; cmd. Command. Type = Command. Type. Table. Direct; cmd. Command. Text = “select * from member”; cmd. Command. Type = Command. Type. Text;

5. 데이터베이스 조작(Command) 5/5 Create. Parameter 매개변수를 사용하는 쿼리문, 저장 프로시저를 위해 매개변수를 지정할

5. 데이터베이스 조작(Command) 5/5 Create. Parameter 매개변수를 사용하는 쿼리문, 저장 프로시저를 위해 매개변수를 지정할 수 있는 Parameter 개체를 생성할 때 호출 Sql. Command cmd = new Sql. Command(); . . . . Sql. Parameter param = cmd. Create. Parameter(); param. Parameter. Name = “@name”; param. Sql. Db. Type = Sql. Db. Type. Varchar; param. Size = 10; param. Value = “korea”;

6. 데이터 가져오기 (Data. Reader) 1/4 Data. Reader 클래스 생성자 public Sql. Data. Reader

6. 데이터 가져오기 (Data. Reader) 1/4 Data. Reader 클래스 생성자 public Sql. Data. Reader Execute. Reader(); Sql. Connection conn = new Sql. Connection(); Sql. Command cmd = new Sql. Command (“selelct * from member”, conn); Sql. Data. Reader read = cmd. Execute. Reader();

6. 데이터 가져오기 (Data. Reader) 2/4 Data. Reader 클래스 속성 속 성 설 명

6. 데이터 가져오기 (Data. Reader) 2/4 Data. Reader 클래스 속성 속 성 설 명 Field. Count 현재 레코드의 필드(수)를 반환 Is. Closed Data. Reader 개체가 닫혀있는지 반환 Records. Affected 데이터를 조작할 경우 DB에서 바뀐 레코드 수 반 환 Data. Reader개체의 반환된 필드를 지정하는 배열 Item Field. Count Sql. Command cmd = new Sql. Command(“select * from memner”, conn); Sql. Data. Reader read = cmd. Excute. Reader(); Console. Write. Line(“member의 전체칼럼 개수 : {0}”, read. Field. Count); Records. Affected Sql. Command cmd = new Sql. Command(“update member set id=david”, conn); Sql. Data. Reader read = cmd. Excute. Reader(); Console. Write. Line(“변경된 레코드 개수 : {0}”, read. Records. Affected);

6. 데이터 가져오기 (Data. Reader) 3/4 Item public object this [string name] {get; }

6. 데이터 가져오기 (Data. Reader) 3/4 Item public object this [string name] {get; } //칼럼(필드)명 사용 public object this [int i] {get; } //서수 사용 -> 서수는 0부터 사용 Sql. Command cmd = new Sql. Command(“select * from memner”, conn); Sql. Data. Reader read = cmd. Excute. Reader(); while(read. Read()) { Console. Write. Line(read[“id”] + “t” + read[칼럼명] or read[“pwd”] + “t” + read[서수] read[“name”]); 두가지 형식으로 사용가능 Console. Write. Line(read[0] + “t” + read[1] + “t” + read[2]); }

7. Data. Table, Data. Column, Data. Row 클래스 System. Data 타입 1/5 설명 Data.

7. Data. Table, Data. Column, Data. Row 클래스 System. Data 타입 1/5 설명 Data. Table 데이터 테이블 Data. Coumn Data. Table에서 특정 Column을 나타낼 때 사용 Data. Row Data. Table에서 특정 Row을 나타낼 때 사용 Data. Column User칼럼을 만들고 Type을 System. String형으로 지정할 경우 (1) Data. Column col = new Data. Column(“User”, Type. Get. Type(“System. String”));

7. Data. Table, Data. Column, Data. Row 클래스 2/5 Data. Column User칼럼을 만들고 Type을

7. Data. Table, Data. Column, Data. Row 클래스 2/5 Data. Column User칼럼을 만들고 Type을 System. String형으로 지정할 경우 (2) Data. Column col = new Data. Column(); col. Data. Type = Type. Get. Type(“System. String”); col. Caption = “데이터칼럼”; col. Column. Name = “User”; col. Allow. DBNull = false; col. Read. Only = true; col. Unique = true; 이름이 NUM이며 Primary Key 속성과 자동증가 속성을 갖는 칼럼 Data. Column col = new Data. Column(); col. Column. Name = “NUM”; col. Auto. Increment = true; col. Auto. Increment. Seed = 100; //자동증가초기값을 100으로 col. Auto. Increment. Step = 10; //한번에 증가되는 값을 10으로

7. Data. Table, Data. Column, Data. Row 클래스 3/5 Data. Row 클래스 생성자 Data.

7. Data. Table, Data. Column, Data. Row 클래스 3/5 Data. Row 클래스 생성자 Data. Row row = Data. Table. New. Row(); //단독생성 불가 Data. Row 클래스 속성 ms-help: // MS. VSCC. v 80/MS. MSDN. v 80/MS. NETDEVFX. v 20. ko/cpref 4/html/T_System_Data. Row_Properties. htm Data. Row. State 열거형 해당 레코드의 상태를 표시할 때 사용 ms-help: // MS. VSCC. v 80/MS. MSDN. v 80/MS. NETDEVFX. v 20. ko/cpref 4/html/T_System_Data. Row. State. htm Data. Row. State를 사용한 예제 (ex)Data. Row. Exam. cs

7. Data. Table, Data. Column, Data. Row 클래스 4/5 Data. Table 클래스 Data. Table은

7. Data. Table, Data. Column, Data. Row 클래스 4/5 Data. Table 클래스 Data. Table은 메모리내에서 존재하는 테이블 Data. Table은 직접작성가능하나, Sql서버나 OLE DB에서 만들어진 데이블정보를 Data. Adapter 클래스와 Data. Set클래스를 참고해 작성 Data. Table 클래스 생성자 Data. Table table = new Data. Table(“Member”); Data. Table 클래스 속성 ms-help: // MS. VSCC. v 80/MS. MSDN. v 80/MS. NETDEVFX. v 20. ko/cpref 4/html/T_System_Data. Table_Properties. htm Primary. Key Data. Table table = new Data. Table(“member”); Data. Column[] pk = new Data. Column[3]; pk[0] = table. Columns[“ID”]; pk[1] = table. Columns[“PWD”]; pk[2] = table. Columns[“NAME”]; table. Primary. Key = pk;

7. Data. Table, Data. Column, Data. Row 클래스 5/5 Data. Table 클래스 메서드 mshelp:

7. Data. Table, Data. Column, Data. Row 클래스 5/5 Data. Table 클래스 메서드 mshelp: //MS. VSCC. v 80/MS. MSDN. v 80/MS. NETDEVFX. v 20. ko/cpref 4/html/T_System_Data. Table_Methods. htm Accept. Changes() Data. Table에 레코드를 추가/갱신/삭제할 경우 내부 데이터는 실제 변경되지 않음 다만, Data. Row의 Row. State 값만이 변경. 실제 테이블에 변경된 내용을 적용하기 위해 Accept. Changes() 호출

9. Data. Set 클래스는 비연결 지향상태에서 질의결과 수행 가능 Data. Set = 메모리 Data.

9. Data. Set 클래스는 비연결 지향상태에서 질의결과 수행 가능 Data. Set = 메모리 Data. Base Data. Set을 통해 실제 DB의 종류와 상관없이 Data. Adapter객체를 통해 메모리상에 해당자료 (테이블, 칼럼, 레코드정보)를 저장 가능 DB에 하나이상의 Table이 있듯이, Data. Set은 1개 이상의 Data. Table개체를 소유 Data. Relation클래스를 이용한 Table간의 관계설정 Data. Set data = new Data. Set(); Data. Column col_Parents = data. Tables[0]. Columns[0]; Data. Column col_Child = data. Tables[1]. Columns[0]; Data. Relation relation = new Data. Relation(“Relation”, col_Parents, col_Child); data. Relation. Add(relation); //data. Relations. Add(“Relation”, data. Tables[0]. Columns[0]), data. Tables[1]. Columns[0]);

10. Data. Adapter 클래스 Data. Reader 클래스 생성자 public Sql. Data. Adapter(); public Sql.

10. Data. Adapter 클래스 Data. Reader 클래스 생성자 public Sql. Data. Adapter(); public Sql. Data. Adapter(Sql. Command select. Command); public Sql. Data. Adapter(string select. Command. Text, Sql. Connection select. Connection); public Sql. Data. Adapter(string select. Command. Text, string select. Connection. String) 속 성 설 명 Delete. Command 데이터를 삭제할 경우 Insert. Command 데이터를 입력할 경우 Select. Command 데이터를 검색할 경우 Update. Command 데이터를 갱신할 경우

10. Data. Adapter 클래스 Delete. Command string sql = “select * from member”; Sql.

10. Data. Adapter 클래스 Delete. Command string sql = “select * from member”; Sql. Connection conn = new Sql. Connection(“Server=localhost; Data. Base=Pubs; uid=sa; pwd=; ”); Sql. Data. Adapter adapter = new Sql. Data. Adapter(sql, conn); adapter. Delete. Command = new Sql. Command(“Delete from member where id = “david”, conn) Data. Reader 클래스 멤버 메소드 설 명 Fill 데이터 원본 테이블을 Data. Set안에 Data. Table에 입력 Fill. Schema 데이터 원본 스키마에 맞게 Data. Set의 Data. Table을 생성 Update Data. Set의 Data. Table에서 변경된 데이터를 원본테이블에 반영

http: //msdn. microsoft. com/vs 2005

http: //msdn. microsoft. com/vs 2005