亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#調(diào)用SQL?Server中有參數(shù)的存儲(chǔ)過(guò)程

 更新時(shí)間:2022年03月04日 08:51:05   作者:.NET開(kāi)發(fā)菜鳥(niǎo)  
這篇文章介紹了C#調(diào)用SQL?Server中有參數(shù)存儲(chǔ)過(guò)程的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、使用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)
        {
            // 存儲(chǔ)過(guò)程名稱(chēng)
            string strProcName = "usp_yngr_getInfectionCard_test";

            //定義存儲(chǔ)過(guò)程的參數(shù)數(shù)組
            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)
                                        };
            // 給存儲(chǔ)過(guò)程參數(shù)數(shù)組賦值
            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>
        /// 通過(guò)存儲(chǔ)過(guò)程獲取數(shù)據(jù)
        /// </summary>
        /// <param name="strProcName">存儲(chǔ)過(guò)程名稱(chēng)</param>
        /// <param name="paraValues">可變的參數(shù)數(shù)組 數(shù)組的個(gè)數(shù)可以為0,也可以為多個(gè)</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;
                    // 設(shè)置CommandType的類(lèi)型
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = conn;
                    conn.Open();

                    if (paraValues != null)
                    {
                        //添加參數(shù)
                        cmd.Parameters.AddRange(paraValues);
                    }

                    // 取數(shù)據(jù)
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("錯(cuò)誤:" + ex.Message + "/r/n跟蹤:" + ex.StackTrace);
                }
                finally
                {
                    conn.Close();
                }
            }
            return dt;
        }
    }
}

二、使用SqlCommandBuilder

在上面的例子中,得到一個(gè)SqlCommand之后要一個(gè)一個(gè)地去設(shè)置參數(shù),這樣很麻煩,幸好SqlCommandBuilder有一個(gè)靜態(tài)的方法:

public static void DeriveParameters(SqlCommand command);

使用這個(gè)方法有兩個(gè)局限性:

  • 1、參數(shù)必須是SqlCommand。
  • 2、該方法只能在調(diào)用存儲(chǔ)過(guò)程的時(shí)候使用。

同時(shí)還要注意到:在使用的時(shí)候,數(shù)據(jù)庫(kù)連接必須是打開(kāi)的。
下面的例子演示如何使用這個(gè)方法設(shè)置存儲(chǔ)過(guò)程的參數(shù):

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)
        {
            // 存儲(chǔ)過(guò)程名稱(chēng)
            string strProcName = "usp_yngr_getInfectionCard_test";
            // 定義參數(shù)類(lèi)
            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;
                    // 設(shè)置CommandType的類(lèi)型
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = conn;
                    conn.Open();

                    // 添加參數(shù)
                    foreach (var item in GetParameters(cmd, objParams))
                    {
                        cmd.Parameters.Add(item);
                    }

                    // 取數(shù)據(jù)
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(dtInit);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("錯(cuò)誤:" + 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);
                        }
                    }
                }

                // 清空所有參數(shù)對(duì)象
                command.Parameters.Clear();
            }

            return collection;
        }
    }
}

示例代碼下載地址:點(diǎn)此下載

到此這篇關(guān)于C#調(diào)用SQL Server中有參數(shù)存儲(chǔ)過(guò)程的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論