非连接环境:用户始终与数据源保持连接操作,一般数据绑定显示使用这种连接。数据库查询操作一般采用非连接环境
用法:
private void myDataBind()
{
string mySQL="select * from table";
SqlConnection objConn = new SqlConnection("Server=.;Database = Norwind;User ID=sa;Password=sa");
SqlDataAdapter objAda = new SqlDataAdapter(mySQL,objConn);
DataSet objDs = new DataSet();
objAda.Fill(objAda);
数据控件绑定数据源 this.GridView1.DataSource = objDs;
数据控件数据绑定 this.GridView1.DataBind();
}
连接环境:一般对数据库进行增、删、改采用连接方式
用法:
private void myUnlinkDataBind()
{
string mySQL = "update table set userid=1";
SqlConnection objConn = new SqlConnection("Server=.;Database=Northwind;User ID=sa;Password=sa");
SqlCommand objCmd = new SqlCommand();
objCmd.Connection = objConn;
objCmd.CommandText = mySQL;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
}
catch
{
}
finally {
objConn.Close();
}
}