C#調(diào)用SQL?Server中有參數(shù)的存儲過程
一、使用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"; //定義存儲過程的參數(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) }; // 給存儲過程參數(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> /// 通過存儲過程獲取數(shù)據(jù) /// </summary> /// <param name="strProcName">存儲過程名稱</param> /// <param name="paraValues">可變的參數(shù)數(shù)組 數(shù)組的個數(shù)可以為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; // 設(shè)置CommandType的類型 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("錯誤:" + ex.Message + "/r/n跟蹤:" + ex.StackTrace); } finally { conn.Close(); } } return dt; } } }
二、使用SqlCommandBuilder
在上面的例子中,得到一個SqlCommand之后要一個一個地去設(shè)置參數(shù),這樣很麻煩,幸好SqlCommandBuilder有一個靜態(tài)的方法:
public static void DeriveParameters(SqlCommand command);
使用這個方法有兩個局限性:
- 1、參數(shù)必須是SqlCommand。
- 2、該方法只能在調(diào)用存儲過程的時候使用。
同時還要注意到:在使用的時候,數(shù)據(jù)庫連接必須是打開的。
下面的例子演示如何使用這個方法設(shè)置存儲過程的參數(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) { // 存儲過程名稱 string strProcName = "usp_yngr_getInfectionCard_test"; // 定義參數(shù)類 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的類型 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("錯誤:" + 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ù)對象 command.Parameters.Clear(); } return collection; } } }
示例代碼下載地址:點此下載
到此這篇關(guān)于C#調(diào)用SQL Server中有參數(shù)存儲過程的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
jQuery結(jié)合C#實現(xiàn)上傳文件的方法
這篇文章主要介紹了jQuery結(jié)合C#實現(xiàn)上傳文件的方法,涉及C#文件上傳的相關(guān)技巧,需要的朋友可以參考下2015-04-04WPF使用DrawingContext實現(xiàn)繪制刻度條
這篇文章主要為大家詳細(xì)介紹了如何利用WPF DrawingContext實現(xiàn)繪制刻度條,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下2022-09-09C#實體對象序列化成Json并讓字段的首字母小寫的兩種解決方法
這篇文章主要介紹了C#實體對象序列化成Json并讓字段的首字母小寫的兩種方法,在這兩種方法中小編比較推薦使用第二種方法,需要的朋友可以參考下2018-06-06C#實現(xiàn)實體類與字符串互相轉(zhuǎn)換的方法
這篇文章主要介紹了C#實現(xiàn)實體類與字符串互相轉(zhuǎn)換的方法,涉及C#字符串及對象的相互轉(zhuǎn)換技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08