搜尋此網誌

2009-07-26

SqlConnection

//宣告DB連線字串
String strConn = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";

//宣告SQL指令
String StrSQL = "SELECT DISTINCT Country FROM Customers";
//建立SQL連結物件
SqlConnection conn = new SqlConnection(strConn);
//建立SQL指令物件
SqlCommand cmd = new SqlCommand(StrSQL, conn);
//指定連結型態
cmd.CommandType = CommandType.Text;
//開啟DB連線
conn.Open();
//建立DB讀取物件,執行SQL指令
SqlDataReader dr = cmd.ExecuteReader();
//讀取
while (dr.Read())
{
comboBox1.Items.Add(dr["Country"].ToString());
}
//結束DB讀取
dr.Close();
//釋放DB讀取物件
dr.Dispose();
//釋放SQL指令物件
cmd.Dispose();
//
comboBox1.SelectedIndex = 0;
//關閉DB連線
conn.Close();
//釋放DB連結物件
conn.Dispose();

沒有留言: