티스토리 뷰

응용프로그래밍/C#

C# MSSQL 접속

공허공자 2011. 9. 15. 14:13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Data;
using System.Data.SqlClient;
 
public class DB_TEST
{
    public static void Main(string[] args)
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString =
            "Server=ip;database=CL_ADMIN;uid=sa;pwd=password;";
 
       try
       {
          conn.Open();
          Console.WriteLine("데이터베이스 연결성공..");
         String log = " SELECT * FROM dbo.OB_TEST"; // 쿼리문
          SqlCommand cmd = new SqlCommand(log, conn); // 적용
           SqlDataReader rd = cmd.ExecuteReader(); // 쿼리 수행
 
          while (rd.Read()) //한줄씩 잃기
          {
            Console.WriteLine(String.Format("{0}, {1}", rd[0],rd[1]));
            //내용 출력하는 부분      
                
          }
         rd.Close();
 
       }
       catch
       {
 
            Console.WriteLine("데이터베이스 연결 실패..");
        }
        finally
        {
            if (conn != null)
            {
                conn.Close();
            }
            Console.WriteLine("데이터베이스 연결해제");
 
        }
    }
}

출처: http://codezip.tistory.com/181

댓글