|
qq |
published in(发表于) 2014/7/11 9:29:40 |
Edit(编辑) |
在C#中调用存储过程
|
|
在C#中调用存储过程
|
|
在C#中调用存储过程
在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方法查询指定信息。示例运行结果如图1和图2所示网站源代码。

图1 插入信息窗体

图2 查询信息窗体
单击【添加信息】按钮时,首先将姓名、性别信息赋值给属性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;
}
}
单击【查询信息】按钮,首先将姓名、性别信息赋给属性str_Name与str_Sex,然后再调用select_Proc方法,select_Proc方法将返回一个DataSet对象用于将结果显示给用户。代码如下:
private void button2_Click(object sender, EventArgs e)
{//本教程来自:http://www.isstudy.com
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;
}
t_People表对应实体,主要通过GET,SET访问器定义属性str_Name与str_Sex。代码如下:
#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
ConDB方法用来生成链接对象,代码如下:
#region//生成链接对象
public SqlConnection ConDB()
{
con = new SqlConnection("server=.;uid=sa;pwd=;database=DB_ADONET");
if (con.State == ConnectionState.Closed)
{//本教程来自:http://www.isstudy.com
con.Open();
}
return con;
}
#endregion
Insert_Proc方法首先获取属性值(str_Name与str_Sex),然后将值传给存储过程(Proc_ InsertOfPelple),最后利用SqlCommand对象的ExecuteNonQuery方法执行存储过程(Proc_Insert OfPelple)完成信息添加功能。网站源代码代码如下:
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)
|
|
|
|