数据表及数据准备:

create table Member
(
	MemberId int primary key identity(1,1),
	MemberAccount nvarchar(20) unique,
	MemberPwd nvarchar(20),
	MemberName nvarchar(20),
	MemberPhone nvarchar(20)
)
truncate table Member

insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
values('liubei','123456','刘备','4659874564')
insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
values('guanyu','123456','关羽','42354234124')
insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
values('zhangfei','123456','张飞','41253445')
insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
values('zhangyun','123456','赵云','75675676547')
insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
values('machao','123456','马超','532523523')

本文以下内容都借助于前面封装的DBHelper类

一、调用exec语句执行存储过程

由于在SQL SERVER内部调用存储过程使用的方式是:

exec 存储过程名 参数1,参数2,参数3...

所以我们可以在C#中调用exec的sql语句,让此sql语句去调用存储过程,严格来说,此种方式并不能称之为C#调用存储过程,本质上仍然是调用的sql语句。

示例:

Winform调用存储过程_存储过程

Winform调用存储过程_存储过程_02

需求: 采用调用存储过程的方式实现数据的显示以及数据的新增。

主要代码:

SQL存储过程代码:

--查询Member表所有数据的存储(没有参数)
create proc procSelectMember
as
	select * from Member
go
exec procSelectMember

--添加会员信息(有输入参数)
create proc procInsertMember
	@acc nvarchar(20),
	@pwd nvarchar(20),
	@memName nvarchar(20),
	@memPhone nvarchar(20)
as
	insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
	values(@acc,@pwd,@memName,@memPhone)
go
exec procInsertMember 'sunwukong','123456','孙悟空','13554856985'

数据显示C#代码:

private void BindData()
{
    DBHelper.PrepareSql("exec procSelectMember");
    this.dataGridView1.DataSource = DBHelper.ExecQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
    BindData();
}

数据新增C#代码:

private void btAdd_Click(object sender, EventArgs e)
{
    DBHelper.PrepareSql(string.Format("exec procInsertMember '{0}','{1}','{2}','{3}'"
        ,this.txtAccount.Text,this.txtPwd.Text,this.txtNickName.Text,this.txtPhone.Text));
    DBHelper.ExecNonQuery();
}

二、直接调用存储过程

调用存储过程需要将CommandType执行命令类型设置为CommandType.StoredProcedure存储过程。

(1)调用没有参数的存储过程

Winform调用存储过程_Winform_03

需求:实现数据的显示。

主要代码:

SQL存储过程代码:

--查询Member表所有数据的存储(没有参数)
create proc procSelectMember
as
	select * from Member
go
--调用
exec procSelectMember

为了支持存储过程,给DBHelper添加方法:

public static void PrepareProc(string sql)
{
    OpenConn(); //打开数据库连接
    adp = new SqlDataAdapter(sql, conn);
    adp.SelectCommand.CommandType = CommandType.StoredProcedure;
}

窗体代码:

private void BindData()
{
    DBHelper.PrepareProc("procSelectMember");
    this.dataGridView1.DataSource = DBHelper.ExecQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
    BindData();
}

(2)调用有输入参数的存储过程

Winform调用存储过程_存储过程_04

需求:实现数据的新增。

主要代码:

SQL存储过程代码:

--添加会员信息(有输入参数)
create proc procInsertMember
	@acc nvarchar(20),
	@pwd nvarchar(20),
	@memName nvarchar(20),
	@memPhone nvarchar(20)
as
	insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
	values(@acc,@pwd,@memName,@memPhone)
go
--调用
exec procInsertMember 'sunwukong','123456','孙悟空','13554856985'

窗体代码:

private void btAdd_Click(object sender, EventArgs e)
{
    DBHelper.PrepareProc("procInsertMember");
    DBHelper.SetParameter("acc", this.txtAccount.Text);
    DBHelper.SetParameter("pwd",this.txtPwd.Text);
    DBHelper.SetParameter("memName", this.txtNickName.Text);
    DBHelper.SetParameter("memPhone", this.txtPhone.Text);
    DBHelper.ExecNonQuery();
}

(3)调用有输入和输出参数的存储过程

Winform调用存储过程_存储过程_05

需求:输入用户名,点击"查询电话"按钮,在下面显示姓名和号码。

主要代码:

SQL存储过程:

--根据账号查询姓名和电话(有输入参数,有输出参数)
create proc procGetInfoByAcc
	@acc nvarchar(20),
	@memName nvarchar(20) output,
	@phone nvarchar(20) output
as
	select @memName = (select MemberName from Member where MemberAccount=@acc)
	select @phone = (select MemberPhone from Member where MemberAccount=@acc)
go
--调用
declare @name nvarchar(20)
declare @phone nvarchar(20)
exec procGetInfoByAcc 'machao',@name output,@phone output
select @name,@phone

为了支持输出参数,给DBHelper添加方法:

/// <summary>
/// 设置输出参数(不指定长度,适合非字符串)
/// </summary>
/// <param name="parameterName">参数名称</param>
/// <param name="dbType">参数类型</param>
public static void SetOutParameter(string parameterName, SqlDbType dbType)
{
    parameterName = "@" + parameterName.Trim();
    SqlParameter parameter = new SqlParameter(parameterName, dbType);
    parameter.Direction = ParameterDirection.Output;
    adp.SelectCommand.Parameters.Add(parameter);
}
/// <summary>
/// 设置输出参数(指定长度,适合字符串)
/// </summary>
/// <param name="parameterName">参数名称</param>
/// <param name="dbType">参数类型</param>
/// <param name="size">参数长度</param>
public static void SetOutParameter(string parameterName, SqlDbType dbType, int size)
{
    parameterName = "@" + parameterName.Trim();
    SqlParameter parameter = new SqlParameter(parameterName, dbType, size);
    parameter.Direction = ParameterDirection.Output;
    adp.SelectCommand.Parameters.Add(parameter);
}
/// <summary>
/// 获取参数内容值
/// </summary>
/// <param name="parameterName">参数名称</param>
/// <returns>参数值</returns>
public static object GetParameter(string parameterName)
{
    parameterName = "@" + parameterName.Trim();
    return adp.SelectCommand.Parameters[parameterName].Value;
}

窗体代码:

private void btSearch_Click(object sender, EventArgs e)
{
    DBHelper.PrepareProc("procGetInfoByAcc");
    DBHelper.SetParameter("acc", this.txtAccount.Text);
    DBHelper.SetOutParameter("memName", SqlDbType.NVarChar, 20);
    DBHelper.SetOutParameter("phone", SqlDbType.NVarChar, 20);
    DBHelper.ExecNonQuery();
    this.lblName.Text = "姓名:" + DBHelper.GetParameter("memName").ToString();
    this.lblPhone.Text = "电话:" + DBHelper.GetParameter("phone").ToString();
}

(4)调用有输入输出参数的存储过程

Winform调用存储过程_存储过程_06

需求:密码升级,传入用户名和密码;如果用户名密码正确,并且密码长度<8,自动升级成8位密码。

主要代码:

SQL存储过程(SQLSERVER中output参数直接传入值即可以做输入参数,也可以做输出参数):

--密码升级,传入用户名和密码,如果用户名密码正确,并且密码长度<8,自动升级成8位密码
--有输入输出参数(密码作为输入参数也作为输出参数)
select FLOOR(RAND()*10) --0-9之间随机数
create proc procPwdUpgrade
@acc nvarchar(20),
@pwd nvarchar(20) output
as
	if not exists(select * from Member where MemberAccount=@acc and MemberPwd=@pwd)
		set @pwd = ''
	else
	begin
		if len(@pwd) < 8
		begin
			declare @len int = 8- len(@pwd)
			declare @i int = 1
			while @i <= @len
			begin
				
				set @pwd = @pwd + cast(FLOOR(RAND()*10) as varchar(1))
				set @i = @i+1
			end
			update Member set MemberPwd = @pwd where MemberAccount=@acc
		end
	end
go
--调用
declare @pwd nvarchar(20) = '123456'
exec procPwdUpgrade 'liubei',@pwd output
select @pwd

为了支持输入输出参数,给DBHelper添加方法:

/// <summary>
/// 设置输入输出参数(不指定长度,适合非字符串)
/// </summary>
/// <param name="parameterName">参数名称</param>
/// <param name="dbType">参数类型</param>
public static void SetInOutParameter(string parameterName, SqlDbType dbType, object parameterValue)
{
    parameterName = "@" + parameterName.Trim();
    SqlParameter parameter = new SqlParameter(parameterName, dbType);
    parameter.Value = parameterValue;
    parameter.Direction = ParameterDirection.InputOutput;
    adp.SelectCommand.Parameters.Add(parameter);
}
/// <summary>
/// 设置输入输出参数(指定长度,适合字符串)
/// </summary>
/// <param name="parameterName">参数名称</param>
/// <param name="dbType">参数类型</param>
/// <param name="size">参数长度</param>
public static void SetInOutParameter(string parameterName, SqlDbType dbType, int size, object parameterValue)
{
    parameterName = "@" + parameterName.Trim();
    SqlParameter parameter = new SqlParameter(parameterName, dbType, size);
    parameter.Value = parameterValue;
    parameter.Direction = ParameterDirection.InputOutput;
    adp.SelectCommand.Parameters.Add(parameter);
}

窗体代码:

//密码升级,传入用户名和密码,
//如果用户名密码正确,并且密码长度<8,自动升级成8位密码
private void btUpgrade_Click(object sender, EventArgs e)
{
    DBHelper.PrepareProc("procPwdUpgrade");
    DBHelper.SetParameter("acc", this.txtAccount.Text);
    DBHelper.SetInOutParameter("pwd", SqlDbType.NVarChar, 20, this.txtPwd.Text);
    DBHelper.ExecNonQuery();
    this.lblNewPwd.Text = DBHelper.GetParameter("pwd").ToString();
}

(5)调用有返回值的存储过程

SQLSERVER存储过程返回值只能是整数。

Winform调用存储过程_数据库_07

需求:实现数据的新增,由SQLSERVER返回执行的状态。

主要代码:

SQL存储过程代码:

--添加会员信息(有返回值)
create proc procInsertMember
	@acc nvarchar(20),
	@pwd nvarchar(20),
	@memName nvarchar(20),
	@memPhone nvarchar(20)
as
	insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)
	values(@acc,@pwd,@memName,@memPhone)
	declare @myErr int = @@error
	if @myErr = 0
		return 1
	else if @myErr = 2627 --唯一约束
		return -1
	else
		return -100
go
--调用
declare @return int
exec @return = procInsertMember 'sunwukong','123456','孙悟空','13554854785'
print @return

为了支持返回值,给DBHelper添加方法:

/// <summary>
/// 设置返回值参数
/// </summary>
/// <param name="parameterName">参数名称</param>
public static void SetReturnParameter(string parameterName)
{
    parameterName = "@" + parameterName.Trim();
    SqlParameter parameter = new SqlParameter();
    parameter.ParameterName = parameterName;
    parameter.Direction = ParameterDirection.ReturnValue;
    adp.SelectCommand.Parameters.Add(parameter);
}

窗体代码:

private void btAdd_Click(object sender, EventArgs e)
{
    try
    {
        DBHelper.PrepareProc("procInsertMember");
        DBHelper.SetParameter("acc", this.txtAccount.Text);
        DBHelper.SetParameter("pwd", this.txtPwd.Text);
        DBHelper.SetParameter("memName", this.txtNickName.Text);
        DBHelper.SetParameter("memPhone", this.txtPhone.Text);
        DBHelper.SetReturnParameter("returnValue");
        DBHelper.ExecNonQuery();
        int result = (int)DBHelper.GetParameter("returnValue");
        if (result == 1)
        	MessageBox.Show("添加成功!");
    }
    catch (Exception ex)
    {
        int result = (int)DBHelper.GetParameter("returnValue");
        if (result == -1)
        	MessageBox.Show("用户名重名了,违反了唯一约束!");
        if (result == -100)
        	MessageBox.Show(ex.Message);
    }
}

技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!

开源库地址,欢迎点亮:

GitHub: https://github.com/ITMingliang

Gitee:  https://gitee.com/mingliang_it

GitLab:  https://gitlab.com/ITMingliang

建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群

Winform调用存储过程_存储过程_08