这篇文章主要讲解了“C#怎么开发Winform程序调用存储”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C#怎么开发Winform程序调用存储”吧!
数据表及数据准备:
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 Memberinsert 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')
一、调用exec语句执行存储过程
由于在SQL SERVER内部调用存储过程使用的方式是:
exec 存储过程名 参数1,参数2,参数3...
所以我们可以在C#中调用exec的sql语句,让此sql语句去调用存储过程,严格来说,此种方式并不能称之为C#调用存储过程,本质上仍然是调用的sql语句。
示例:
需求:采用调用存储过程的方式实现数据的显示以及数据的新增。
主要代码:
SQL存储过程代码:
--查询Member表所有数据的存储(没有参数)create proc procSelectMemberasselect * from Membergoexec procSelectMember--添加会员信息(有输入参数)create proc procInsertMember@acc nvarchar(20),@pwd nvarchar(20),@memName nvarchar(20),@memPhone nvarchar(20)asinsert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)values(@acc,@pwd,@memName,@memPhone)goexec 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)调用没有参数的存储过程
需求:实现数据的显示。
主要代码:
SQL存储过程代码:
--查询Member表所有数据的存储(没有参数)create proc procSelectMemberasselect * from Membergo--调用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)调用有输入参数的存储过程
需求:实现数据的新增。
主要代码:
SQL存储过程代码:
--添加会员信息(有输入参数)create proc procInsertMember@acc nvarchar(20),@pwd nvarchar(20),@memName nvarchar(20),@memPhone nvarchar(20)asinsert 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)调用有输入和输出参数的存储过程
需求:输入用户名,点击"查询电话"按钮,在下面显示姓名和号码。
主要代码:
SQL存储过程:
--根据账号查询姓名和电话(有输入参数,有输出参数)create proc procGetInfoByAcc@acc nvarchar(20),@memName nvarchar(20) output,@phone nvarchar(20) outputasselect @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 outputselect @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)调用有输入输出参数的存储过程
需求:密码升级,传入用户名和密码;如果用户名密码正确,并且密码长度<8,自动升级成8位密码。
主要代码:
SQL存储过程(SQLSERVER中output参数直接传入值即可以做输入参数,也可以做输出参数):
--密码升级,传入用户名和密码,如果用户名密码正确,并且密码长度<8,自动升级成8位密码--有输入输出参数(密码作为输入参数也作为输出参数)select FLOOR(RAND()*10) --0-9之间随机数create proc procPwdUpgrade@acc nvarchar(20),@pwd nvarchar(20) outputasif not exists(select * from Member where MemberAccount=@acc and MemberPwd=@pwd)set @pwd = ''elsebeginif len(@pwd) < 8begindeclare @len int = 8- len(@pwd)declare @i int = 1while @i <= @lenbeginset @pwd = @pwd + cast(FLOOR(RAND()*10) as varchar(1))set @i = @i+1endupdate Member set MemberPwd = @pwd where MemberAccount=@accendendgo--调用declare @pwd nvarchar(20) = '123456'exec procPwdUpgrade 'liubei',@pwd outputselect @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存储过程返回值只能是整数。
需求:实现数据的新增,由SQLSERVER返回执行的状态。
主要代码:
SQL存储过程代码:
--添加会员信息(有返回值)create proc procInsertMember@acc nvarchar(20),@pwd nvarchar(20),@memName nvarchar(20),@memPhone nvarchar(20)asinsert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone)values(@acc,@pwd,@memName,@memPhone)declare @myErr int = @@errorif @myErr = 0return 1else if @myErr = 2627 --唯一约束return -1elsereturn -100go--调用declare @return intexec @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); }}
感谢各位的阅读,以上就是“C#怎么开发Winform程序调用存储”的内容了,经过本文的学习后,相信大家对C#怎么开发Winform程序调用存储这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!