(在這寫下來,防止以后忘記)
在VS2012中新建一個Windows窗口應用程序,並在Form中放置DataGridView和Button兩個控件,在Button的單擊響應事件中連接數據庫:
private void button1_Click(object sender, EventArgs e) { String connsql = "server=.;database=MyDBName;integrated security=SSPI"; // 數據庫連接字符串,database設置為自己的數據庫名,以Windows身份驗證 try { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connsql; conn.Open(); // 打開數據庫連接 String sql = "select * from student"; // 查詢語句 SqlDataAdapter myda = new SqlDataAdapter(sql, conn); // 實例化適配器 DataTable dt = new DataTable(); // 實例化數據表 myda.Fill(dt); // 保存數據 dataGridView1.DataSource = dt; // 設置到DataGridView中 conn.Close(); // 關閉數據庫連接 } } catch (Exception ex) { MessageBox.Show("錯誤信息:" + ex.Message, "出現錯誤"); } }
點擊進入CSDN博客,查看C#連接SQL數據庫常用連接字符串:
http://blog.csdn.net/fredrickhu/archive/2009/12/08/4961799.aspx