sqlcommand对象的有几个操作方法

2024-11-23 11:07:46
推荐回答(1个)
回答1:

总结了一下,在任何时候都可以使用sqlcommand对象来完成您想要的操作.
使用sqlcommand对象来返回数据集合的方法
string strconn="data source=billgates;initial catalog=test;integrated security=SSPI;";
SqlConnection conn=new SqlConnection(strconn);
conn.Open();
SqlCommand sqlcmd=new SqlCommand();
sqlcmd.CommandText ="select * from student";
sqlcmd.Connection=conn;
SqlDataAdapter adp=new SqlDataAdapter(sqlcmd);
DataTable dt=new DataTable();
adp.Fill(dt);
dataGrid1.DataSource=dt;

使用sqlcommand对象来返回SQL执行正确与否
string strconn="data source=billgates;initial catalog=test;integrated security=SSPI;";
SqlConnection conn=new SqlConnection(strconn);
conn.Open();
SqlCommand sqlcmd=new SqlCommand();
sqlcmd.CommandText ="select * from student";
sqlcmd.Connection=conn;
try
{
sqlcmd.ExecuteNonQuery();
MessageBox.Show("success");
}
catch
{
MessageBox.Show("false");
}

使用sqlcommand对象来操作存储过程
string strconn="data source=billgates;initial catalog=test;integrated security=SSPI;";
SqlConnection conn=new SqlConnection(strconn);
conn.Open();
SqlCommand sqlcmd=new SqlCommand();
sqlcmd.CommandText ="a";
sqlcmd.CommandType=CommandType.StoredProcedure ;
sqlcmd.Connection=conn;
sqlcmd.Parameters.Add("@param1",textBox1.Text.Trim());
sqlcmd.Parameters.Add("@param2",textBox2.Text.Trim());
sqlcmd.Parameters.Add("@param3",textBox3.Text.Trim());

SqlDataAdapter adp=new SqlDataAdapter(sqlcmd);
DataTable dt=new DataTable();
adp.Fill(dt);
dataGrid1.DataSource=dt;