using用法和SqlCommand認識
阿新 • • 發佈:2019-01-27
using三種用法
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = null;
//實現了IDisposable介面的物件,可以使用using進行資源管理(如:SqlDataAdapter、SqlDataReader、DataSet、SqlCommand)
//using會在作用於結束的時候自動呼叫物件的dispose方法
//1.
using (SqlConnection conn = new SqlConnection("server=.;database=Login;uid=sa;pwd=coder" ))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "sql 語句";
cmd.Connection = conn;
conn.Open();
cmd.ExecuteScalar();
//conn.Close();//關閉的是程式和資料庫之間的連線,
//conn.Dispose();//這個方法內部是呼叫了close方法的
}
//2.
using (conn = new SqlConnection("連線字串" )) { }
//3.
conn = new SqlConnection("連線字串");
using (conn) { }
}
SqlCommand認識
//兩種方式功能一樣
SqlCommand cmd=new SqlCommand(); cmd.Connetion=conn; cmd.CommandText="";
SqlCommand cmd = new SqlCommand("",conn);
//兩種方式功能一樣
SqlCommand cmd=new SqlCommand();cmd.Connection=conn;
SqlCommand cmd = conn.CreateCommand();