티스토리 뷰

응용프로그래밍/C#

C# MSSQL 접속

공허공자 2011. 9. 15. 14:13
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

댓글