C#

[C#]SqlConnection 예제

선영아 사랑해 2016. 3. 24. 16:28


using System.Data.SqlClient;


SqlConnection conn;


private void Form1_Load(object sender, EventArgs e)

{

string CONNECTION_STRING = "Server=*****;UID=*****;PWD=*******;Database=**********";

//Server에는 DB 접속 IP를 입력. 내 컴퓨터의 DB에 접속인경우에는 localhost 입력

//UID, PWD는 DB 접속 할 계정정보 입력

//Database는 접속 할 DB 명칭 입력


conn = new SqlConnection(CONNECTION_STRING);

try
{
       conn.Open();
}
catch (Exception ex)
{
       MessageBox.Show(ex.ToString());
 }

}


//조회

private void btnSelect_Click(object sender, EventArgs e)

{

SqlCommand cmd = conn.CreateCommand();


cmd.CommandText = "SELECT * FROM usertable";


SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

adapter.Fill(ds);


datagridView.DataSource = ds.Tables[0];

}


//연결해제

private void btnClose_Click(object sender, EventArgs e)
{
       try
       {
            if (conn.State == ConnectionState.Open)
                conn.Close();

            conn.Dispose();
      }
      catch (Exception ex)
      {
           MessageBox.Show(ex.ToString());
       }
}

'C#' 카테고리의 다른 글

[C#]Mouse Drag and Drop Control 생성 예제  (0) 2016.03.25
[C#]문자열을 char 배열 변환 예제  (0) 2016.03.25
SATO Barcode Command(SBPL)  (0) 2016.03.24
[C#]DataTable Sort 예제  (0) 2016.03.23
[C#]DataGrid Row Delete, Row Select 예제  (0) 2016.03.23