服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#调用SQL Server中有参数的存储过程

C#调用SQL Server中有参数的存储过程

2023-02-17 11:58.NET开发菜鸟 C#

这篇文章介绍了C#调用SQL Server中有参数存储过程的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、使用SqlParameter的方式

代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Collections.ObjectModel;
using System.Reflection;
 
namespace ExecuteProcBySQLServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btn_LoadData_Click(object sender, EventArgs e)
        {
            // 存储过程名称
            string strProcName = "usp_yngr_getInfectionCard_test";
 
            //定义存储过程的参数数组
            SqlParameter[] paraValues = {
                                        new SqlParameter("@BeginTime",SqlDbType.VarChar),
                                        new SqlParameter("@EndTime",SqlDbType.VarChar),
                                        new SqlParameter("@DateType",SqlDbType.Int),
                                        new SqlParameter("@PtName",SqlDbType.VarChar),
                                        new SqlParameter("@PtChartNo",SqlDbType.VarChar),
                                        new SqlParameter("@DeptCode",SqlDbType.VarChar),
                                        new SqlParameter("@CheckedStatus",SqlDbType.Int)
                                        };
            // 给存储过程参数数组赋值
            paraValues[0].Value = "2017-06-01";
            paraValues[1].Value = "2017-07-01";
            paraValues[2].Value = 1;
            paraValues[3].Value = "";
            paraValues[4].Value = "";
            paraValues[5].Value = "";
            paraValues[6].Value = 1;
 
            this.dgv_Demo.DataSource = LoadData(strProcName, paraValues);
 
        }
 
        /// <summary>
        /// 通过存储过程获取数据
        /// </summary>
        /// <param name="strProcName">存储过程名称</param>
        /// <param name="paraValues">可变的参数数组 数组的个数可以为0,也可以为多个</param>
        /// <returns></returns>
        private DataTable LoadData(string strProcName, params object[] paraValues)
        {
            DataTable dt = new DataTable();
            string strConn = ConfigurationManager.ConnectionStrings["HealthHospInfection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(strConn))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = strProcName;
                    // 设置CommandType的类型
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = conn;
                    conn.Open();
 
                    if (paraValues != null)
                    {
                        //添加参数
                        cmd.Parameters.AddRange(paraValues);
                    }
 
                    // 取数据
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message + "/r/n跟踪:" + ex.StackTrace);
                }
                finally
                {
                    conn.Close();
                }
            }
            return dt;
        }
    }
}

二、使用SqlCommandBuilder

在上面的例子中,得到一个SqlCommand之后要一个一个地去设置参数,这样很麻烦,幸好SqlCommandBuilder有一个静态的方法:

?
1
public static void DeriveParameters(SqlCommand command);

使用这个方法有两个局限性:

  • 1、参数必须是SqlCommand。
  • 2、该方法只能在调用存储过程的时候使用。

同时还要注意到:在使用的时候,数据库连接必须是打开的。
下面的例子演示如何使用这个方法设置存储过程的参数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
 
namespace ExecuteProcBySQLServer
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
 
        private void btn_LoadData_Click(object sender, EventArgs e)
        {
            // 存储过程名称
            string strProcName = "usp_yngr_getInfectionCard_test";
            // 定义参数类
            object objParams = new
            {
                BeginTime = "2017-06-01",
                EndTime = "2017-07-01",
                DateType = 1,
                PtName = "",
                PtChartNo = "",
                DeptCode = "",
                CheckedStatus = 1
            };
 
            this.dgv_Demo.DataSource = LoadData(strProcName,objParams);
        }
 
        private DataTable LoadData(string strProcName,object objParams)
        {
            DataTable dtInit = new DataTable();
            string strConn = ConfigurationManager.ConnectionStrings["HealthHospInfection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(strConn))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = strProcName;
                    // 设置CommandType的类型
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = conn;
                    conn.Open();
 
                    // 添加参数
                    foreach (var item in GetParameters(cmd, objParams))
                    {
                        cmd.Parameters.Add(item);
                    }
 
                    // 取数据
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(dtInit);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message + "/r/n跟踪:" + ex.StackTrace);
                }
                finally
                {
                    conn.Close();
                }
            }
            return dtInit;
        }
 
        private Collection<SqlParameter> GetParameters(SqlCommand command, object objParam)
        {
            Collection<SqlParameter> collection = new Collection<SqlParameter>();
            if (objParam != null)
            {
                // 使用反射获取属性
                PropertyInfo[] properties = objParam.GetType().GetProperties();
                SqlCommandBuilder.DeriveParameters(command);
                //int index = 0;
                foreach (SqlParameter parameter in command.Parameters)
                {
                    foreach (PropertyInfo property in properties)
                    {
                        if (("@" + property.Name.ToLower()).Equals(parameter.ParameterName.ToLower()))
                        {
                            parameter.Value = property.GetValue(objParam, null);
                            collection.Add(parameter);
                        }
                    }
                }
 
                // 清空所有参数对象
                command.Parameters.Clear();
            }
 
            return collection;
        }
    }
}

示例代码下载地址:点此下载

到此这篇关于C#调用SQL Server中有参数存储过程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/dotnet261010/p/7428513.html

延伸 · 阅读

精彩推荐
  • C#C# 使用modbus 读取PLC 寄存器地址的方法

    C# 使用modbus 读取PLC 寄存器地址的方法

    今天通过本文给大家介绍C# 使用modbus 读取PLC 寄存器地址的方法,使用的组件Nmodbus,文中通过实例代码给大家介绍的非常详细,需要的朋友参考下吧...

    peiban19949042022-12-07
  • C#C#时间格式转换为时间戳的方法步骤

    C#时间格式转换为时间戳的方法步骤

    这篇文章主要介绍了C#时间格式转换为时间戳的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋...

    iDaDi8132022-11-02
  • C#C#利用NPOI操作Excel(单元格设置)

    C#利用NPOI操作Excel(单元格设置)

    这篇文章主要为大家详细介绍了C#利用NPOI操作Excel实现单元格设置,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    出征的企鹅8562023-02-09
  • C#C#如何使用Task执行异步操作

    C#如何使用Task执行异步操作

    这篇文章主要介绍了C#如何使用Task执行异步操作,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下...

    HarryK9742022-11-16
  • C#C#多态的三种实现方式(小结)

    C#多态的三种实现方式(小结)

    这篇文章主要介绍了C#多态的三种实现方式(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面...

    令狐掌门7572022-11-09
  • C#C#多线程系列之任务基础(三)

    C#多线程系列之任务基础(三)

    本文详细讲解了C#多线程的任务基础,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    痴者工良11212022-12-29
  • C#C#实现的Excel文件操作类实例

    C#实现的Excel文件操作类实例

    这篇文章主要介绍了C#实现的Excel文件操作类,结合具体实例形式分析了C#数据库及Excel文件相关操作技巧,需要的朋友可以参考下...

    songkexin4182022-01-11
  • C#C#制作网站挂机程序的实现示例

    C#制作网站挂机程序的实现示例

    本文主要介绍了C#制作网站挂机程序,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    寒茗清雾11532022-12-07