日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#調用SQL?Server中有參數的存儲過程_C#教程

作者:.NET開發菜鳥 ? 更新時間: 2022-05-04 編程語言

一、使用SqlParameter的方式

代碼:

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

        }

        /// 
        /// 通過存儲過程獲取數據
        /// 
        /// 存儲過程名稱
        /// 可變的參數數組 數組的個數可以為0,也可以為多個
        /// 
        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有一個靜態的方法:

public static void DeriveParameters(SqlCommand command);

使用這個方法有兩個局限性:

  • 1、參數必須是SqlCommand。
  • 2、該方法只能在調用存儲過程的時候使用。

同時還要注意到:在使用的時候,數據庫連接必須是打開的。
下面的例子演示如何使用這個方法設置存儲過程的參數:

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 GetParameters(SqlCommand command, object objParam)
        {
            Collection collection = new Collection();
            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;
        }
    }
}

示例代碼下載地址:點此下載

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

欄目分類
最近更新