2016년 12월 29일 목요일

[닷넷교육,C#교육,실무교육학원추천_탑크리에듀]ADO.NET DataBase 연결(DB Connection)4 - SqlConnection 클래스

ADO.NET DataBase 연결(DB Connection)4 - SqlConnection 클래스
 
System.Data.SqlClient 네임스페이스는 .NET Framework Data Provider for SQL Server이며 MS-SQL을 다루기 위한 여러 개의 클래스가 있는데 그  중 하나가 SqlConnectiom 이며 SQL Servert에 대한 연결을 나타내며 이 클래스는 상속될 수 없다.
 
SqlConnection클래스는 다음과 같은 생성자(Constructor)들을 갖는다.
 
[SqlConnection Constructor]

public sealed class SqlConnection : DbConnection, 
 ICloneable
 
public SqlConnection();

public SqlConnection(string ConnectionString) : 연결 문자열을 포함한 SqlConnection 클래스의 새 인스턴스를 초기화
 
SqlConnection 클래스는, 필요한 이름 공간(Name Space)이 다르다는 점을 제외한 다면 OleDbConnection 클래스와 흡사한 형태라고 할 수 있다. 두 클래스는 모두 IDbConnection이라는 인터페이스(Interface)를 구현 하고 있기 때문이다.
 
OleDbConnection을 생성하기 위해서는 최소한 Provider 속성은 지정해야 하며 SqlConnection을 생성하기 위해서는 데이터소스 속성은 지정해야 한다.
 
.NET Framework Data Provider for SQL Server는 자체 프로토콜을 사용하여 SQL Server와 통신하므로 즉 ODBC 계층을 추가하지 않기 때문에 SQL Server에 연결할 때 ODBC DSN(데이터 소스 이름)의 사용을 지원하지 않는다.

[SqlConnection Public Property]

- ConnectionString
 
데이터소스에 연결하기 위한 세부적인 정보를 담는 스트링. private static void OpenSqlConnection()
{
    string connectionString = GetConnectionString();
    using (SqlConnection connection = new SqlConnection())
    {
        connection.ConnectionString = connectionString;
        connection.Open();
        Console.WriteLine("State: {0}", connection.State);
        Console.WriteLine("ConnectionString: {0}",
            connection.ConnectionString);
    }
}
static private string GetConnectionString()
{
    // To avoid storing the connection string in your code, 
    // you can retrieve it from a configuration file.
    return "Data Source=MSSQL1;Initial Catalog=AdventureWorks;"
        + "Integrated Security=true;";
}
 
- ConnectionTimeout 
 
연결 시도를 취소하거나 에러를 내기 전까지, Open() 메쏘드(Method)가 기다리는 시간(초). 
 
SqlConnection cn=New SqlConnection(
"Data Source=MSSQL1;" +
"Initial Catalog=Northwind;" +
"Integrated Security=SSPI;" +
"Connect Timeout=60;")
Console.WriteLine("{0}", cn.ConnectionTimeout); 
Database 커넥션(Connection)이 열렸을 때 사용되는 데이터베이스 이름을 담고 있는 프로퍼티(Property) 리턴. private static void ChangeSqlDatabase(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("Database: {0}", connection.Database);
        connection.ChangeDatabase("Northwind");
        Console.WriteLine("Database: {0}", connection.Database);
    }
}

- DataSource
 
연결할 SQL Server 인스턴스의 이름을 가져옵니다 [Access DB]
"Data Source=mdb파일경로및이름;"

[SQL Server]
"Data Source=localhost;"
ServerVersion 데이터베이스 서버(Database Server)의 버전 정보 리턴. SqlConnection cn=New SqlConnection(
"Data Source=localhost;" +
"Initial Catalog=Northwind;
cn.Open();
Console.WriteLine("{0}", cn.ServerVersion);
State 현재 연결상태(Connection State)를 나타내는 프로퍼티(Property) 표시. (Read-Only) System.Data.ConnectionState
Closed, Open, Connecting, Executing, Fetching, Broken

ConnectionString에 관해서 좀 더 살펴보면, 대략 다음과 같은 파라미터(Parameter)들을 볼 수 있습니다.
 
[SqlConnection Parameters]
 
- Application Name   

응용 프로그램 이름이 제공되지 않으면 응용 프로그램의 이름이거나 '.NET SQLClient 데이터 공급자'.

- AttachDBFilename  -or-
extended properties  -or-
Initial File Name   

연결할 수 있는 데이터베이스의 전체 경로 이름을 포함한 주 데이터베이스 파일의 이름

- Connect Timeout  -or-
Connection Timeout  

시도를 종료하고 오류를 생성할 때까지 서버에 대한 연결을 대기하는 시간(초).
유효한 값은 0보다 크거나 같고 2147483647보다 작거나 같다.

 - Connection Lifetime 

 연결이 풀로 반환되면 만든 시간을 현재 시간과 비교하여 그 간격(초)이 Connection Lifetime에서 지정한 값을 초과하면 연결이 소멸됩니다. 클러스터 환경(Clustered Configuration)  에서 유용하게 사용.
0보다 크거나 같고 2147483647보다 작거나 같다.

- Current Language: 데이터베이스 서버 경고 또는 오류 메시지에 사용하는 언어를 설정합니다.
 
- Data Source  -or-
Server  -or-
Address  -or-
Addr  -or-
Network Address   

SQL 서버 인스턴스(Instance)의 네트웍 주소이름.

- Enlist:'true' 'true'로 세팅되어 있는 경우, SQL Server Connection Pooler는 자동으로 해당 커넥션을 생성 하고 쓰레드의 트랜잭션 컨텍스트(Context)에  연결을 추가.
 
- Initial Catalog  -or-
Database   

데이터베이스 이름,  < 128글자

- Integrated Security  -or-
Trusted_Connection 
 
false 이면 연결할 때 사용자 ID 및 암호를 지정한다. true 이면 현재의 Windows 계정 자격 증명이 인증에 사용된다.

- Max Pool Size 100 :풀에서 허용되는 연결의 최대 개수.

Min Pool Size 0 풀에서 허용되는 최소 연결 개수입니다.
 
- MultipleActiveResultSets : 'false' true 이면 응용 프로그램에서 여러 MARS(Multiple Active Result Set)를 유지할 수 있습니다. false 이면 응용 프로그램에서 한 일괄 작업의 모든 결과 집합을 처리하거나 취소해야만 해당 연결에서 다른 일괄 작업을 실행할 수 있다.

이 키워드는 .NET Framework 버전 1.0 또는 1.1에서는 지원되지 않는다.
 
 
- Network Library  -or-
Net 

SQL Server의 인스턴스에 연결하는 데 사용하는 네트워크 라이브러리. 지원되는 값은 다음과 같다.
 
dbnmpntw(명명된 파이프)
dbmsrpcn(멀티프로토콜, Windows RPC)
dbmsadsn(Apple Talk)
dbmsgnet(VIA)
dbmslpcn(공유 메모리)
dbmsspxn(IPX/SPX)
dbmssocn(TCP/IP)
Dbmsvinn(Banyan Vines)
 
 아래 예제에서 네트워크 라이브러리는 Win32 Winsock TCP/IP(dbmssocn)이며 1433 포트가 사용된다.
Network Library=dbmssocn;Data Source=000.000.000.000,1433;

- Packet Size : SQL Server의 인스턴스와 통신하는 데 사용하는 네트워크 패킷의 크기(바이트).
패킷 크기는 512보다 크거나 같고 32767보다 작거나 같다.(기본값 8192)

- Password  -or-
Pwd   로그온할 SQL Server 계정에 대한 암호.

- Persist Security Info :'false' False인 경우, Password와 같은 보안 관련 정보(Security-Sensitive Information)는 리턴 되지 않음.
 
- Pooling : 'true' true인 경우, 커넥션 풀에서 연결 객체를 끌어오게 됨. 커넥션 풀이 존재하지 않으면 새로 생성한다.
 
- User ID:  사용자 계정.
 
- Workstation ID : the local computer name SQL Server에 연결하는 워크스테이션의 이름.
ID는 128자 미만으로 제한.
 

[SqlConnection Public Method]
 
- BeginTransaction 
 
특정 데이터 소스(Data Source)에서 SQL Transaction 객체를 생성. 
private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;
        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");
        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;
        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();
            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);
            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}

- ChangeDatabase : 현재 연결된 데이터베이스를 요청된 데이터베이스로 전환.  
 
private static void ChangeSqlDatabase(string connectionString)
{
    // Assumes connectionString represents a valid connection string
    // to the AdventureWorks sample database.
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("Database: {0}", connection.Database);
        connection.ChangeDatabase("Northwind");
        Console.WriteLine("Database: {0}", connection.Database);
    }
}

- ChangePassword : 연결 문자열에 지정된 사용자의 SQL Server 암호를 제공된 새 암호로 변경 
 
- ClearAllPools : 연결 풀을 모두 비움 
 
- ClearPool : 지정된 연결과 관련된 연결 풀을 비웁니다. 
 
- Close : 연결(Connection)을 닫고, 연관된 모든 자원(resources)을 시스템에 반환. 
 
cn.Open();
cn.Close();
 
- CreateCommand : 해당 연결 객체(Connection Object)를 대상으로 OleDbCommand 객체를 생성함. 
cn.Open();
OleDbCommand cmd=cn.CreateCommand();
 
- Open : 커넥션 스트링(Connection String)에 정의된 데이터베이스를 열리게 함. 
SqlConnection cn=New SqlConnection(
"Data Source=localhost;" +
"Initial Catalog=Northwind;
);
cn.Open();

[OleDbConnection Public Event]
 
Event Name Description
InfoMessage SQL Server가 경고나 정보 메시지를 반환할 때 발생다.
Disposed Dispose 메서드를 호출하여 구성 요소가 삭제되는 경우 발생
StateChange 연결 상태(Connection State) 변화가 생겼을 때 발생.
 

댓글 없음:

댓글 쓰기