C#連線SQL Server 2012
阿新 • • 發佈:2019-02-19
新建一個“連線”按鈕,取名btSql_Connect_Click,在按鈕Click事件中寫如下程式碼:
//連線SQL Server的test資料庫 //string connectionString = "Data Source=localhost;Database=test;uid=sa;pwd=xxx"; string connectionString = "Data Source=localhost;Database=test;Integrated Security=true"; string sql = "select count(*) from Student"; SqlConnection connection = new SqlConnection(connectionString); if (connection != null) { connection.Open(); //SqlCommand物件,執行操作資料錄的命令 SqlCommand command = new SqlCommand(sql, connection); int totalcount = Convert.ToInt32(command.ExecuteScalar()); MessageBox.Show("test表中共有" + totalcount + "條資料"); connection.Close(); } else { MessageBox.Show("連線SQL Server失敗!"); }