当前位置: 代码网 > it编程>编程语言>C# > C# WinForms存储过程操作数据库的实例讲解

C# WinForms存储过程操作数据库的实例讲解

2025年04月24日 C# 我要评论
在 c# winforms 中通过存储过程操作数据库是提高应用性能和安全性的重要手段。以下为详细解析和完整示例:一、存储过程基础优势:预编译执行,性能更优防止sql注入攻击减少网络传输数据量便于集中管

在 c# winforms 中通过存储过程操作数据库是提高应用性能和安全性的重要手段。

以下为详细解析和完整示例:

一、存储过程基础

优势

  • 预编译执行,性能更优
  • 防止sql注入攻击
  • 减少网络传输数据量
  • 便于集中管理业务逻辑

创建示例​(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()
end

二、c# 调用流程

1. 数据库连接配置

using system.data;
using system.data.sqlclient;

string connectionstring = "server=.;database=yourdb;integrated security=true;";

2. 执行存储过程(增删改)

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;
        }
    }
}

3. 查询数据

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)
{
    // 常规异常处理
}

性能优化

  • 存储过程内使用set nocount on
  • 避免在存储过程中进行复杂计算
  • 合理创建索引

五、典型存储过程类型

  1. 数据操作:insert/update/delete
  2. 查询返回:单结果集/多结果集
  3. 分页查询:使用row_number()实现
  4. 业务处理:包含事务的多表操作

完整示例可在实际项目中直接使用,注意根据实际情况:

  1. 修改连接字符串
  2. 调整参数类型和长度
  3. 添加具体的业务逻辑处理
  4. 完善异常日志记录功能

通过存储过程实现数据访问层,可使winforms应用程序更易维护,同时提升安全性和执行效率。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com