212人参与 • 2025-04-24 • C#
在 c# winforms 中通过存储过程操作数据库是提高应用性能和安全性的重要手段。
以下为详细解析和完整示例:
优势:
创建示例(sql server):
create procedure sp_addemployee
@name nvarchar(50),
@age int,
@email nvarchar(100),
@newid int output
as
begin
insert into employees (name, age, email)
values (@name, @age, @email)
set @newid = scope_identity()
endusing system.data; using system.data.sqlclient; string connectionstring = "server=.;database=yourdb;integrated security=true;";
public bool addemployee(string name, int age, string email, out int newid)
{
using (sqlconnection conn = new sqlconnection(connectionstring))
{
try
{
conn.open();
using (sqlcommand cmd = new sqlcommand("sp_addemployee", conn))
{
cmd.commandtype = commandtype.storedprocedure;
// 输入参数
cmd.parameters.add("@name", sqldbtype.nvarchar, 50).value = name;
cmd.parameters.add("@age", sqldbtype.int).value = age;
cmd.parameters.add("@email", sqldbtype.nvarchar, 100).value = email;
// 输出参数
sqlparameter outputparam = new sqlparameter("@newid", sqldbtype.int)
{
direction = parameterdirection.output
};
cmd.parameters.add(outputparam);
cmd.executenonquery();
newid = (int)outputparam.value;
return true;
}
}
catch (sqlexception ex)
{
messagebox.show($"数据库错误: {ex.message}");
newid = -1;
return false;
}
}
}public datatable getemployees(int minage)
{
datatable dt = new datatable();
using (sqlconnection conn = new sqlconnection(connectionstring))
{
using (sqlcommand cmd = new sqlcommand("sp_getemployees", conn))
{
cmd.commandtype = commandtype.storedprocedure;
cmd.parameters.addwithvalue("@minage", minage);
sqldataadapter da = new sqldataadapter(cmd);
da.fill(dt);
}
}
return dt;
}public bool updateemployeetransaction(int id, string newname)
{
using (sqlconnection conn = new sqlconnection(connectionstring))
{
conn.open();
sqltransaction transaction = conn.begintransaction();
try
{
using (sqlcommand cmd = new sqlcommand("sp_updateemployee", conn, transaction))
{
cmd.parameters.addwithvalue("@id", id);
cmd.parameters.addwithvalue("@newname", newname);
cmd.executenonquery();
}
transaction.commit();
return true;
}
catch (exception ex)
{
transaction.rollback();
messagebox.show($"操作失败: {ex.message}");
return false;
}
}
}参数安全
资源管理
using (sqlconnection conn = new sqlconnection(...))
using (sqlcommand cmd = new sqlcommand(...))
{
// 自动释放资源
}错误处理
try
{
// 数据库操作
}
catch (sqlexception ex)
{
// 处理数据库特有错误
if (ex.number == 547) // 外键约束错误
}
catch (exception ex)
{
// 常规异常处理
}性能优化
完整示例可在实际项目中直接使用,注意根据实际情况:
通过存储过程实现数据访问层,可使winforms应用程序更易维护,同时提升安全性和执行效率。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论