//增加、刪除、更新、查詢公用
string MyConn = "server=127.0.0.1;uid=數據庫登錄名;pwd=密碼;database=數據庫的名字;Trusted_Connection=no";
SqlConnection MyConnection = new SqlConnection(MyConn);
1、增加
string MyInsert = "想要執行的sql語句";
SqlCommand MyCommand = new SqlCommand(MyInsert, MyConnection);
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
2、刪除
string MyDelete = "想要執行的sql語句";
SqlCommand MyCommand = new SqlCommand(MyDelete, MyConnection);
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
3、更新
string MyUpdate = "想要執行的sql語句";
SqlCommand MyCommand = new SqlCommand(MyUpdate, MyConnection);
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
4、查詢
MyConn.Open();
SqlDataAdapter dap = new SqlDataAdapter("想要執行的sql語句",MyConn);
DataSet ds = new DataSet();//實例化DataSet類
dap.Fill(ds, "Table");//添加SQL語句並執行
dataGridView1.DataSource = ds.Tables[0].DefaultView;//顯示數據