Presentation is loading. Please wait.

Presentation is loading. Please wait.

C#에서 데이터베이스 연동 방법.

Similar presentations


Presentation on theme: "C#에서 데이터베이스 연동 방법."— Presentation transcript:

1 C#에서 데이터베이스 연동 방법

2 1. ADO.NET 데이터 공급자 소개

3 1.1 ADO.NET 데이터 공급자의 개요 C#에서 ADO 이용한 DB 연동 ADO 라이브러리 SQL Server 2005
응용 프로그램 Stored DB

4 1.1 ADO.NET 데이터 공급자의 개요 (계속) Microsoft SQL Server, OLE DB, XML등의 데이터 원본에 대한 일관적인 접근방법을 제공 ADO.NET 데이터 공급자 응용 프로그램과 데이터 원본이 통신할 수 있게 하는 ADO.NET 아키텍쳐의 핵심 구성 요소 응용 프로그램과 데이터 원본간의 연결 브릿지 역할을 함 핵심 개체 Connection: 특정 데이터 원본과의 연결을 생성 Command: 데이터 원본에 대해서 명령을 수행 DataReader: 빠른 전진 전용, 읽기 전용 데이터 액세스를 제공 DataAdapter: DataSet을 채우고 데이터 원본을 변경

5 1.2 ADO.NET의 기본 구조 ADO.Net의 구조 Database 공급자(Provider) DataSet
응용 프로그램 Connection 공급자(Provider) Command DataSet SqlClient OleDb OracleClient Odbc Database DataReader DataAdapter

6 1.2 ADO.NET의 기본 구조 (계속) ADO.NET의 구성 .NET Data Provider DataSet Command
연결지향 DataReader Database Connection DataAdapter 비연결지향 DataSet XML DataSet

7 1.3 ADO.NET 데이터 공급자 유형 SQL Server 데이터 공급자 (SqlClient) OLEDB 데이터 공급자
중간 계층(OLE DB나 ODBC) 없이 바로 SQL Server와 통신 OLEDB 데이터 공급자 OLEDB 통해 COM interop layer를 통해 연결 ODBC 데이터 공급자 ODBC 드라이버를 통해 연동 Oracle 데이터 공급자 Oracle 클라이언트 연결 소프트웨어를 이용해서 Oracle 연동

8 1.3 ADO.NET 데이터 공급자 유형(계속) 데이터 공급자의 종류 SQL Server 데이터 공급자
SQL Server 중심의 데이터 전송 프로토콜(Tabular Data Stream)을 이용해서 SQL Server와 통신 SQL Server에 접근할 때 OLE DB나 ODBC 연결 계층을 추가하지 않고 직접 연결 Microsoft SQL Server 7.0 버전이나 이후 버전을 사용하는 응용 프로그램에 권장 코드에 다음 “using”구문을 포함하여 사용 OLEDB 데이터 공급자 네이티브 OLEDB를 이용해서 COM interop 레이어를 통해 데이터에 액세스함 OLE DB를 지원하는 공급자에 대한 중간 계층(middle tier) 응용 프로그램에 권장 using System.Data.SqlClient; using System.Data.SqlClient;

9 1.3 ADO.NET 데이터 공급자 유형(계속) ODBC 데이터 공급자 (1.1버전에 새로 도입)
네이티브ODBC 드라이버 관리자를 이용해서 ODBC 데이터 원본에 액세스 ODBC 데이터 공급자는 로컬 트랜잭션과 분산트랜잭션 모두 지원 ODBC 데이터 원본을 사용하는 응용 프로그램에 권장 코드에 다음 “using”구문을 포함하여 사용 Oracle 데이터 공급자 (1.1 버전에 새로 도입) Oracle 클라이언트 연결 소프트웨어를 이용해서 Oracle 데이터 원본에 액세스 Oracle 클라이언트 소프트웨어 버전 8.1.7이나 이후 버전을 지원 Oracle을 데이터 원본으로 하는 응용 프로그램에 권장 네임스페이스를 프로젝트 | 추가 | 참조 메뉴를 이용해서 System.Data.OracleClient.dll 어셈블리를 선택해서 추가 using System.Data.Odbc; using System.Data.OracleClient;

10 1.4 ADO.NET 데이터 공급자 연결 문자열 연결 문자열 응용 프로그램에서 원본 데이터와 연결하기 위해 연결 문자열 지정
ConnectionString 속성은 연결이 닫혀있을 경우에만 할당이 가능 연결 문자열은 일련의 키=값 쌍이 세미콜론으로 구분된 형태로 구성 ConnectionString의 구성 Data Source나 server 연결하려는 Server 인스턴스의 명칭이나 네트워크 주소 Integrated Security나 Trusted_Connection False로 설정: User ID와 Password는 연결정보에 지정 True로 설정: 인증을 위해 현재 윈도우 계정의 자격증명을 사용 User ID 로그인 계정 Password나 Pwd 계정의 암호 Initial Catalog나 Database 데이터베이스 이름

11 2. SqlClient 데이터 공급자 개요

12 2.1 SqlClient 데이터 공급자 사용 방법 SQL DB 연결 순서 1. 네임스페이스 명시
using System.Data.SqlClient; 2. Connection 객체 생성(연결 프로퍼티 설정) SqlConnection conn; conn = new SqlConnection("Server=dibi.kangwon.ac.kr; user id = ;password=4315; database=DB4315"); 3. Connecton 연결 conn.Open(); 4. 작업수행( SQL 쿼리 작업) -- sqlCommand 객체를 사용하여 질의 수행 5. 연결 닫기 conn.Close();

13 2.2 SqlClient 공급자의 Connection 클래스
using System.Data.SqlClient; SqlConnection conn = new SqlConnection("Data Source = dibi.kangwon.ac.kr; Initial Catalog = DB4315; User ID = ; Password = 4315"); conn.open(); Connection의 속성 conn.Database conn.DataSource conn.ServerVersion conn.State conn.WorkstationId 1. Database = DB4315 2. DataSource = localhost 3. DataServerVersion = 4. State = Open 5. WorkstationID = JABOOK-1 6. State = Closed

14 2.3 SqlCommand 클래스 SqlCommand 클래스 SqlCommand에서 사용할 수 있는 명령들
DB에 필요한 명령을 전달하거나 그 결과를 받아올 때 사용하는 클래스 SqlCommand에서 사용할 수 있는 명령들 단일 값 및 레코드 셋을 반환하는 SELECT, CREATE, ALERT, DROP 같은 DLL(Data Definition Language) 명령 GRANT, DENY, REVOKE 같은 DCL(Data Control Language) 명령 INSERT, UPDATE, DELETE 같은 DML(Data Modification Language) 명령

15 2.3 SqlCommand 클래스 (계속) SqlCommand 클래스 주요 함수 ExecuteNonQuery()
ExecuteReader() 쿼리를 Connection에 보내고 SqlDataReader를 생성 ExecuteScalar() 쿼리를 실행하고 쿼리에서 반환된 결과 집합의 첫번째 행의 첫번째 열 반환 ExecuteXmlReader() 쿼리를 Connection에 보내고 XmlReader 객체를 생성

16 2.4 SqlCommand의 ExecuteNonQuery
데이터베이스의 쿼리(Query) 중 Select 명령을 제외한 대부분의 명령을 처리할 수 있다. ExecuteNonQuery()의 사용 Connection 생성 및 Open string conStr = “dibi.kangwon.ac.kr; user id = …… "; SqlConnection conn = new SqlConnection(conStr); conn.Open(); SqlCommnad 생성 string createQuery = "create table Address ( id int, name char(20), addr char(40))"; SqlCommand comm = new SqlCommand(createQuery, conn); SqlCommand 실행 comm.ExecuteNonQuery(); Connection Close conn.Close(); 반환 값 : 처리된 행의 개수

17 예제 프로그램(1) ……. using System.Data.SqlClient; namespace ado_intro {
public partial class Form1 : Form SqlConnection conn = new SqlConnection("Server=dibi.kangwon.ac.kr; user id = ;password=4315; database=DB4315"); public Form1() InitializeComponent(); } <다음 슬라이드에 계속>

18 예제 프로그램(1) - 계속 private void Form1_Load(object sender, EventArgs e) {
conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "insert into Customers values('123', 'Company 123', 'Kim', 'Prof', 'Hyoja Dong')"; comm.ExecuteNonQuery(); MessageBox.Show("데이타 삽입 완료"); }

19 2.5 SqlCommand의 Parameter(Insert문장)
반복적인 쿼리 작업이나 쿼리가 복잡할 경우에 주로 사용한다. Parameter 변수를 선언하는 방법 string query ="Insert into SqlCommand comm = new SqlCommand(query, conn); Parameter 타입을 지정하는 예 SqlDbType.TinyInt); SqlDbType.Char); SqlDbType.Char); Parameter의 값 설정 = 6; = "HongGilDDong"; = "Seoul"; SqlCommand의 실행 comm.ExecuteNonQuery(); DataAdapter DataReader Command Connection Transaction Parameter .Net Data Provider의 구성요소 SelectCommand InsertCommand UpdateCommand DeleteCommand

20 멤버 .NET Type 설명 BigInt Int64 64비트 부호화 정수 Binary Byte[ ]
1~ 8,000바이트 이진 데이터의 고정 길이 스트림 Bit Boolean 0,1 및 null 참조일 수 있는 부호 없는 숫자값 Char String 1~8,000자 유니코드 제외 문자의 고정 길이 스트림 DateTime 정확성 3.33밀리초, ~ 일 날짜 및 시간 데이터 Decimal ~ 고정 전체 자릿수 및 소수 자릿수값 Float Double -1.79E+308~1.79E +308 부동 소수점 숫자 Image 0~ 바이트 이진 데이터의 가변 길이 스트림 Int Int32 32비트 부호 있는 정수 Money 정확성 통화 단위의 10000분의 1 -263(또는 -922,337,203,685, )~263-1 통화값 NChar 1~4.000자 유니코드 문자의 고정 길이 스트림 NText 230 – 1까지 유니코드 데이터의 가변 길이 스트림 NVarChar 1~4.000자 유니코드 문자의 가변 길이 스트림 Real Single -3.40E+38 ~3.40E +38 부동 소수점 숫자 SmallDateTime 정확성 1초, ~ 일인 날짜 및 시간 데이터 SmallInt Int16 16비트 부호 있는 정수 SmallMoney 정확성이 통화 단위의 1000분의 10 범위 -214, ~+214, 까지인 통화값 Text 최대 231-1자 유니코드 제외 데이터의 가변길이 스트림 Timestamp yyyymmddhhmmss 형식의 날짜 및 시간 데이터 TinyInt Byte 8비트 부호 없는 정수 UniqueIdentifier Guid GUID(Globally Unique IDentifier) VarBinary 1~8,000바이트 이진 데이터의 가변 길이 스트림 VarChar 1~8,000문자 비유니코드 문자의 가변 길이 스트림 Variant Object SQL Server 값 Empty 및 Null, 숫자, 문자열, 이진 또는 날짜 데이터를 포함할 수 있는 특수 데이터 형식

21

22 2.6 SqlCommand의 ExecuteReader
Select 쿼리를 처리할 때 사용하는 함수 SqlDataReader를 얻기 위한 절차 1. 네임스페이스 명시 using System.Data.SqlClient; 2. Connection 객체 생성 : 생성자에게 연결 정보 전달, 연결 프로퍼티 설정 SqlConnection conn = new SqlConnection(Server=localhost; user id=sa; password=; database=northwind"); 3. Connecton 연결 conn.Open(); 4. Command 객체 생성 : 실행할 쿼리와 Connection을 인수로 함 SqlCommand comm = new SqlCommand("select * from 테이블명", conn); 5. 데이터 읽어오기 SqlDataReader reader = comm.ExecuteReader(); 6. 작업수행 7. 연결 닫기 conn.Close(); Connection Database SqlCommand (Select 문장) SqlDataReader SqlCommand의 SqlDataReader ExecuteReader()의 호출

23 2.7 SqlCommand의 Parameter(Select문장)
데이터베이스 Connection 생성과 Open string conStr = "Server=localhost;user id=sa;password=;database=northwind"; string query = "select * from Address where or SqlConnection conn = new SqlConnection(conStr); conn.Open(); Command 생성과 Parameter 타입 지정 SqlCommand comm = new SqlCommand(query, conn); SqlDbType.Char); SqlDbType.Char); Command의 Parameter 값 설정 = "서울시"; = "대전시"; 데이터 읽어오기 SqlDataReader sr = comm.ExecuteReader(); while(sr.Read()){ Console.WriteLine(sr.GetInt32(0)+"|"+ sr.GetString(1).Trim()+"|"+ sr.GetString(2) ); } SqlDataReader와 Connection 닫기 sr.Close(); conn.Close();


Download ppt "C#에서 데이터베이스 연동 방법."

Similar presentations


Ads by Google