陈斌彬的技术博客

Stay foolish,stay hungry

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;