it编程 > 编程语言 > C#

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

11人参与 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()
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)
{
    // 常规异常处理
}

性能优化

五、典型存储过程类型

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

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

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

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

总结

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

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

使用C#进行音频处理的完整指南(从播放到编辑)

04-24

C#和Java互相调用的方法小结

04-24

C#中高效的多线程并行处理实现方式详解

04-24

C#中ExcelDataReader的具体使用

04-24

C# 配置文件app.config 和 web.config详解

04-24

C# 窗口过程消息处理 WndProc的方法详解

04-24

猜你喜欢

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

发表评论