1 / 23

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

C# 에서 데이터베이스 연동 방법. 1. ADO.NET 데이터 공급자 소개. SQL Server 2005. C# 응용 프로그램. ADO 라이브러리. Stored DB. 1.1 ADO.NET 데이터 공급자의 개요. C# 에서 ADO 이용한 DB 연동. 1.1 ADO.NET 데이터 공급자의 개요 ( 계속 ). Microsoft SQL Server, OLE DB, XML 등의 데이터 원본에 대한 일관적인 접근방법을 제공 ADO.NET 데이터 공급자

marc
Download Presentation

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

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. C#에서 데이터베이스 연동 방법

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

  3. SQL Server 2005 C# 응용 프로그램 ADO 라이브러리 Stored DB 1.1 ADO.NET 데이터 공급자의 개요 • C#에서 ADO 이용한 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의 구조 응용 프로그램 Connection 공급자(Provider) Command DataSet SqlClient OleDb OracleClient Odbc Database DataReader DataAdapter

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

  7. 1.3 ADO.NET 데이터 공급자 유형 • SQL Server 데이터 공급자 (SqlClient) • 중간 계층(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”구문을 포함하여 사용

  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”구문을 포함하여 사용

  10. 1.4 ADO.NET 데이터 공급자 연결 문자열 • 연결 문자열 • 응용 프로그램에서 원본 데이터와 연결하기 위해 연결 문자열 지정 • ConnectionString 속성은 연결이 닫혀있을 경우에만 할당이 가능 • 연결 문자열은 일련의 키=값 쌍이 세미콜론으로 구분된 형태로 구성 • ConnectionString의 구성

  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 =20024315;password=4315; database=DB4315"); 3. Connecton 연결 • conn.Open(); 4. 작업수행( SQL 쿼리 작업) -- sqlCommand 객체를 사용하여 질의 수행 5. 연결 닫기 • conn.Close();

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

  14. 2.3 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() • SQL 문을 실행하고 처리된 행의 개수를 반환 • ExecuteReader() • 쿼리를 Connection에 보내고 SqlDataReader를 생성 • ExecuteScalar() • 쿼리를 실행하고 쿼리에서 반환된 결과 집합의 첫번째 행의 첫번째 열 반환 • ExecuteXmlReader() • 쿼리를 Connection에 보내고 XmlReader 객체를 생성

  16. 2.4 SqlCommand의 ExecuteNonQuery • 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 =20024315;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. .Net Data Provider의 구성요소 Connection Transaction Command Parameter DataReader SelectCommand InsertCommand DataAdapter UpdateCommand DeleteCommand 2.5 SqlCommand의 Parameter(Insert문장) • SqlCommand의 Parameter • 반복적인 쿼리 작업이나 쿼리가 복잡할 경우에 주로 사용한다. • Parameter 변수를 선언하는 방법 • string query ="Insert into Address values (@ID, @Name, @Address)"; • SqlCommand comm = new SqlCommand(query, conn); • Parameter 타입을 지정하는 예 • comm.Parameters.Add("@ID", SqlDbType.TinyInt); • comm.Parameters.Add("@Name", SqlDbType.Char); • comm.Parameters.Add("@Address", SqlDbType.Char); • Parameter의 값 설정 • comm.Parameters["@ID"].Value = 6; • comm.Parameters["@Name"].Value = "HongGilDDong"; • comm.Parameters["@Address"].Value = "Seoul"; • SqlCommand의 실행 • comm.ExecuteNonQuery();

  20. SqlCommand의 SqlDataReader Connection SqlDataReader Database SqlCommand (Select 문장) ExecuteReader()의 호출 2.6 SqlCommand의 ExecuteReader • 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();

  21. 2.7 SqlCommand의 Parameter(Select문장) • 데이터베이스 Connection 생성과 Open • string conStr = "Server=localhost;user id=sa;password=;database=northwind"; • string query = "select * from Address where addr=@addr1 or addr=@addr2"; • SqlConnection conn = new SqlConnection(conStr); • conn.Open(); • Command 생성과 Parameter 타입 지정 • SqlCommand comm = new SqlCommand(query, conn); • comm.Parameters.Add("@addr1", SqlDbType.Char); • comm.Parameters.Add("@addr2", SqlDbType.Char); • Command의 Parameter 값 설정 • comm.Parameters["@addr1"].Value = "서울시"; • comm.Parameters["@addr2"].Value = "대전시"; • 데이터 읽어오기 • 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();

More Related