在C#中调用存储过程
调用存储过程时主要会涉及到两种状况:一种是执行而不需要返回值,例如删除、修改等;另一种是执行并且要求有返回值,例如查询。在C#中调用存储过程时主要会用到两个类SqlCommand和SqlDataAdapter,SqlCommand类的CommandType属性可以获取或设置要对数据源执行的Transact-SQL语句或存储过程。当SqlCommand与存储过程关联起来之后就可以通过SqlCommand类来执行。另一种执行方法则是通过SqlDataAdapter类的Fill方法,SqlDataAdapter类的Fill方法不仅会执行存储过程同时会将结果放入结果集中。
示例 C#中调用存储过程
首先创建一个用于添加信息的存储过程(Proc_InsertOfPelple)与一个用于查找信息的存储过程(Proc_SelectOfPelple)。然后定义一个数据操作类(ClsDBProcControl)用于实现对表(t_People)的各种操作,ClsDBProcControl类中包括ConDB方法、Insert_Proc方法、select_Proc方法以及t_People表对应的实体类,在程序运行时当用户单击【添加信息】按钮时,将把姓名和性别信息赋值给t_People表的属性,然后通过调用Insert_Proc方法向数据表中插入新信息,当单击【查询信息】按钮时,把姓名和性别信息赋值给t_People表的属性,然后通过调用select_Proc方法查询指定信息。
程序代码如下。
单击【添加信息】按钮时首先将姓名、性别信息赋给属性str_Name与属性str_Sex,然后再调用Insert_Proc方法实现插入信息功能。代码如下:
private void button1_Click(object sender, EventArgs e) { ClsDB.ClsDBProcControl CBDP = new OptDB.ClsDB.ClsDBProcControl(); CBDP.str_Name = this.textBox2.Text.Trim().ToString(); CBDP.str_Sex = this.textBox3.Text.Trim().ToString(); if (CBDP.Insert_Proc(CBDP)) { MessageBox.Show("插入成功"); CBDP.str_Name =string.Empty; CBDP.str_Sex = string.Empty; this.dataGridView1.DataSource = CBDP.select_Proc(CBDP).Tables[0].DefaultView; } } |
private void button2_Click(object sender, EventArgs e) { ClsDB.ClsDBProcControl CBDP = new OptDB.ClsDB.ClsDBProcControl(); CBDP.str_Name = this.textBox2.Text.Trim().ToString(); CBDP.str_Sex = this.textBox3.Text.Trim().ToString(); this.dataGridView1.DataSource = CBDP.select_Proc(CBDP).Tables[0].DefaultView; } |
#region//表对应的实体 private string strName; public string str_Name { get { return this.strName; } set { strName = value; } } private string strSex; public string str_Sex { get { return this.strSex; } set { strSex = value; } } #endregion |
#region//生成连接对象 public SqlConnection ConDB() { con = new SqlConnection("server=.;uid=sa;pwd=;database=DB_ADONET"); if (con.State == ConnectionState.Closed) { con.Open(); } return con; } #endregion |
public bool Insert_Proc(ClsDBProcControl CDB) { using(cmd = new SqlCommand()) { try { cmd.CommandText = "Proc_InsertOfPelple"; cmd.Connection = ConDB(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@tb_PName", SqlDbType.VarChar); cmd.Parameters["@tb_PName"].Value = CDB.str_Name; cmd.Parameters.Add("@tb_PSex", SqlDbType.VarChar).Value = CDB.str_Sex; cmd.ExecuteNonQuery(); return true; } catch { return false; } finally { if (con.State == ConnectionState.Open) { con.Close(); con.Dispose(); } } } } |
public DataSet select_Proc(ClsDBProcControl CDB) { try { SqlDataAdapter da = new SqlDataAdapter("Proc_SelectOfPelple", ConDB()); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.Add("@tb_PName", SqlDbType.VarChar).Value = CDB.str_Name; da.SelectCommand.Parameters.Add("@tb_PSex", SqlDbType.VarChar).Value = CDB.str_Sex; DataSet ds = new DataSet(); da.Fill(ds); return ds; } catch { return null; } } |
注意:在类内声名了两个对象,一个是cmd(SqlCommand对象),另一个是con(SqlConnection对象)。