C#完整执行存储过程的代码加实例
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
?
namespace TestWindow
{
??? public class StoreProcedure
??? {
??????? // 連接字符串。
??????? private string connectionString;
??????? // 存儲過程名稱。
??????? private string storeProcedureName;
??????? <summary>
??????? /// 初始化 DataAccessHelper.StoreProceduer 對象。
??????? /// </summary>
??????? /// <param name="connectionString">數據庫連接字符串。</param>
??????? public StoreProcedure(string connectionString)
??????? {
??????????? this.connectionString = connectionString;
??????? }
??????? <summary>
??????? /// 初始化 DataAccessHelper.StoreProceduer 對象。
??????? /// </summary>
??????? /// <param name="connectionString">數據庫連接字符串。</param>
??????? /// <param name="storeProcedureName">存儲過程名稱。</param>
??????? public StoreProcedure(string storeProcedureName, string connectionString)
??????? {
??????????? this.connectionString = connectionString;
??????????? this.storeProcedureName = storeProcedureName;
??????? }
??????? <summary>
??????? /// 獲取或設置存儲過程名稱。
??????? /// </summary>
??????? public string StoreProcedureName
??????? {
??????????? get { return this.storeProcedureName; }
??????????? set { this.storeProcedureName = value; }
??????? }
??????? <summary>
??????? /// 執行操作類(Insert/Delete/Update)存儲過程。
??????? /// </summary>
??????? /// <param name="paraValues">傳遞給存儲過程的參數值列表。</param>
??????? /// <returns>受影響的行數。</returns>
??????? public int ExecuteNonQuery(params object[] paraValues)
??????? {
??????????? using (SqlConnection connection = new SqlConnection(this.connectionString))
??????????? {
??????????????? SqlCommand command = this.CreateSqlCommand(connection);
??????????????? try
??????????????? {
??????????????????? this.DeriveParameters(command);
??????????????????? this.AssignParameterValues(command, paraValues);
??????????????????? connection.Open();
??????????????????? int affectedRowsCount = command.ExecuteNonQuery();
??????????????????? return affectedRowsCount;
??????????????? }
??????????????? catch
??????????????? {
??????????????????? throw;
??????????????? }
??????????? }
??????? }
??????? <summary>
??????? /// 執行存儲過程,返回 System.Data.DataTable。
??????? /// </summary>
??????? /// <param name="paraValues">傳遞給存儲過程的參數值列表。</param>
??????? /// <returns>包含查詢結果的 System.Data.DataTable。</returns>
??????? public DataTable ExecuteDataTable(params object[] paraValues)
??????? {
??????????? using (SqlConnection connection = new SqlConnection(this.connectionString))
??????????? {
??????????????? SqlCommand command = this.CreateSqlCommand(connection);
??????????????? try
??????????????? {
??????????????????? this.DeriveParameters(command);
??????????????????? this.AssignParameterValues(command, paraValues);
??????????????????? SqlDataAdapter adapter = new SqlDataAdapter(command);
??????????????????? DataTable dataTable = new DataTable();
??????????????????? adapter.Fill(dataTable);
??????????????????? return dataTable;
??????????????? }
??????????????? catch
??????????????? {
??????????????????? throw;
??????????????? }
??????????? }
??????? }
??????? <summary>
??????? /// 執行存儲過程,填充指定的 System.Data.DataTable。
??????? /// </summary>
??????? /// <param name="dataTable">用于填充查詢結果的 System.Data.DataTable。</param>
??????? /// <param name="paraValues">傳遞給存儲過程的參數值列表。</param>
??????? public void ExecuteFillDataTable(DataTable dataTable, params object[] paraValues)
??????? {
??????????? using (SqlConnection connection = new SqlConnection(this.connectionString))
??????????? {
??????????????? SqlCommand command = this.CreateSqlCommand(connection);
??????????????? try
??????????????? {
??????????????????? this.DeriveParameters(command);
??????????????????? this.AssignParameterValues(command, paraValues);
??????????????????? connection.Open();
??????????????????? SqlDataAdapter adapter = new SqlDataAdapter(command);
??????????????????? adapter.Fill(dataTable);
??????????????? }
??????????????? catch
??????????????? {
??????????????????? throw;
??????????????? }
??????????? }
??????? }
??????? <summary>
??????? /// 執行存儲過程返回 System.Data.SqlClient.SqlDataReader,
??????? /// 在 System.Data.SqlClient.SqlDataReader 對象關閉時,數據庫連接自動關閉。
??????? /// </summary>
??????? /// <param name="paraValues">傳遞給存儲過程的參數值列表。</param>
??????? /// <returns>包含查詢結果的 System.Data.SqlClient.SqlDataReader 對象。</returns>
??????? public SqlDataReader ExecuteDataReader(params object[] paraValues)
??????? {
??????????? using (SqlConnection connection = new SqlConnection(this.connectionString))
??????????? {
??????????????? SqlCommand command = this.CreateSqlCommand(connection);
??????????????? try
??????????????? {
??????????????????? this.DeriveParameters(command);
??????????????????? this.AssignParameterValues(command, paraValues);
??????????????????? connection.Open();
??????????????????? return command.ExecuteReader(CommandBehavior.CloseConnection);
??????????????? }
??????????????? catch
??????????????? {
??????????????????? throw;
??????????????? }
??????????? }
??????? }
??????? <summary>
??????? /// 執行查詢,并返回查詢所返回的結果集中第一行的第一列。忽略其他列或行。
??????? /// </summary>
??????? /// <param name="paraValues">傳遞給存儲過程的參數值列表。</param>
??????? /// <returns>結果集中第一行的第一列或空引用(如果結果集為空)。</returns>
??????? public object ExecuteScalar(params object[] paraValues)
??????? {
??????????? using (SqlConnection connection = new SqlConnection(this.connectionString))
??????????? {
??????????????? SqlCommand command = this.CreateSqlCommand(connection);
??????????????? try
??????????????? {
??????????????????? this.DeriveParameters(command);
??????????????????? this.AssignParameterValues(command, paraValues);
??????????????????? connection.Open();
??????????????????? object result = command.ExecuteScalar();
??????????????????? //string r = command.Parameters[1].Value.ToString();
??????????????????? return result;
??????????????? }
??????????????? catch
??????????????? {
??????????????????? throw;
??????????????? }
??????????? }
??????? }
??????? <summary>
??????? /// 從在 System.Data.SqlClient.SqlCommand 中指定的存儲過程中檢索參數信息并填充指定的
??????? /// System.Data.SqlClient.SqlCommand 對象的 System.Data.SqlClient.SqlCommand.Parameters 集? 合。
??????? /// </summary>
??????? /// <param name="sqlCommand">將從其中導出參數信息的存儲過程的 System.Data.SqlClient.SqlCommand 對象。</param>
??????? internal void DeriveParameters(SqlCommand sqlCommand)
??????? {
??????????? try
??????????? {
??????????????? sqlCommand.Connection.Open();
??????????????? SqlCommandBuilder.DeriveParameters(sqlCommand);
??????????????? sqlCommand.Connection.Close();
??????????? }
??????????? catch
??????????? {
??????????????? if (sqlCommand.Connection != null)
??????????????? {
??????????????????? sqlCommand.Connection.Close();
??????????????? }
??????????????? throw;
??????????? }
??????? }
??????? // 用指定的參數值列表為存儲過程參數賦值。
??????? private void AssignParameterValues(SqlCommand sqlCommand, params object[] paraValues)
??????? {
??????????? if (paraValues != null)
??????????? {
??????????????? if ((sqlCommand.Parameters.Count - 1) != paraValues.Length)
??????????????? {
??????????????????? throw new ArgumentNullException("The number of parameters does not match number of values for stored procedure.");
??????????????? }
??????????????? for (int i = 0; i < paraValues.Length; i++)
??????????????? {
??????????????????? sqlCommand.Parameters[i + 1].Value = (paraValues[i] == null) ? DBNull.Value : paraValues[i];
??????????????? }
??????????? }
??????? }
??????? // 創建用于執行存儲過程的 SqlCommand。
??????? private SqlCommand CreateSqlCommand(SqlConnection connection)
??????? {
??????????? SqlCommand command = new SqlCommand(this.storeProcedureName, connection);
??????????? command.CommandType = CommandType.StoredProcedure;
??????????? return command;
??????? }
//-------------------------------------這一部分是我完善的,因為沒有執行后返回存儲過程中的返回值的函數-----------------------
??????? /// <summary>
??????? /// 執行存儲過程,返回存儲過程定義的返回值,注意存儲過程中參數(paraValues)如果為返回值賦為空,其它值位置對應好
??????? /// </summary>
??????? /// <param name="output">返回存儲過程中定義的返回值數組</param>
??????? /// <param name="outParaNum">存儲過程中返回值的個數</param>
??????? /// <param name="paraValues">存儲過程全部參數值</param>
??????
??????? public void ExecProcOutput(out object[] output, int outParaNum, params object[] paraValues)
??????? {
??????????? using (SqlConnection connection = new SqlConnection(this.connectionString))
??????????? {
??????????????? SqlCommand command = this.CreateSqlCommand(connection);
??????????????? output = new object[outParaNum];//存儲過程中返回值的個數
??????????????? try
??????????????? {
??????????????????? this.DeriveParameters(command);
??????????????????? this.AssignParameterValues(command, paraValues);
??????????????????? connection.Open();
??????????????????? command.ExecuteNonQuery();
??????????????????? for (int i = 0; i < outParaNum; i++)//將存儲過程返回的參數值返回到程序中
??????????????????? {
??????????????????????? output[i] = command.Parameters[1].Value;
??????????????????? }???????????????????
??????????????? }
??????????????? catch
??????????????? {
??????????????????? throw;
??????????????? }
??????????? }
??????? }
??? }
}
調用實例:
網上也沒有個具體的調用實例,我這里加一個大家參考
存儲過程:使用student數據庫,數據很簡單自己去看就可以了
創建存儲過程:第一個是有返回值的,第二個是普通查詢
if exists(select name from sysobjects where name='checkUserName' and type='p')
?drop proc checkUserName
go
create proc checkUserName
?(@checkResult int output,
? @userName varchar(20),
? @userID varchar(20))
as
?if exists(select * from student_table where sname=@userName and studentID=@userID)
?set @checkResult=1 --通過驗證
?else if exists(select * from student_table where sname=@userName)
?set @checkResult=2 --用戶密碼錯誤
?else
?set @checkResult=0 --用戶不存在
return isNull(@checkResult,2)
go
--以下是執行第一個存儲過程在sql server 2005中
declare @checkResult int --聲明一個返回值的變量
exec checkUserName @checkResult output,'g','123' --執行
select case @checkResult --select?
?when 1 then '成功'
?when 0 then '不存在'
? when 2 then '密碼不正確'
? end as? '驗證結果'
--第二個存儲過程,普通查詢
use student
if exists(select * from sysobjects where type='p' and name='studentProc')
?drop proc studentProc
go
create proc studentProc
?(@studentName varchar(20),
? @studentID varchar(20))
as
?select * from student_table where sname=@studentName and studentID=@studentID
--執行存儲過程
go
exec studentProc 'g','123'
--------------------以下是在C# vs 2005中使用上面我面定義的類來執行存儲過程------------
界面,很簡單就是測試
?private void button1_Click(object sender, EventArgs e)
??????? {
???????????
??????????? SqlConnection conn = new SqlConnection(connString);
??????????? SqlCommand cmd = new SqlCommand();
//---------注釋部分是我普通的執行存儲過程的語句,很繁瑣吧...
??????????? //cmd.Connection = conn;
??????????? //conn.Open();
??????????? //cmd.CommandText = "checkUserName";
??????????? //cmd.CommandType = CommandType.StoredProcedure;
??????????? //cmd.Parameters.Add("@userName", SqlDbType.VarChar);
??????????? //cmd.Parameters["@userName"].Value = this.textBox1.Text.Trim();
??????????? //cmd.Parameters.Add("@userID", SqlDbType.VarChar);
??????????? //cmd.Parameters["@userID"].Value = this.textBox2.Text.Trim();
??????????? //cmd.Parameters.Add("@checkResult", SqlDbType.Int);
??????????? //cmd.Parameters["@checkResult"].Direction = ParameterDirection.Output;
??????????? //cmd.ExecuteNonQuery();studentProc
//---------使用執行存儲過程幫手的類來完成.........簡單啊!
??????????? StoreProcedure sp = new StoreProcedure("checkUserName", connString);//類的對象
??????????? Object[] paraValues = new object[3];//注意,這里是存儲過程中全部的參數,一共有三個,還要注意順序啊,返回值是第一個,那么賦值時第一個參數就為空
????????????
??????????? paraValues[1] = this.textBox1.Text.Trim();//從第二個參數開始賦值
??????????? paraValues[2] = this.textBox2.Text.Trim();
??????????? object[] output注意,這里是用來保存,存儲過程中定義的返回值
??????????? sp.ExecProcOutput(out output,1, paraValues);//調用我們前面定義的方法,這里我就隨便寫了一個,能完成功能,大家改進
??????????? //object o = sp.ExecuteScalar(paraValues);//這個是查詢的那個存儲過程調用,很簡單,不多說了
?
//---------下面就是驗證了...看看,這樣做是不是很簡單的執行了存儲過程.....
??????????? switch (Convert.ToInt32(output[0]))
??????????? {
??????????????? case 0:
??????????????????? this.label4.Text = "用戶不存在";
??????????????????? break;
??????????????? case 1:
??????????????????? this.label4.Text = "登錄成功";
??????????????????? break;
??????????????? case 2:
??????????????????? this.label4.Text = "密碼不正確";
??????????????????? break;
??????????????? default:
??????????????????? break;
??????????? }
??????? }
好了..就到這里...我這也是看貼子做完寫點感受..也增加自己的印象.............積累中..............
總結
以上是生活随笔為你收集整理的C#完整执行存储过程的代码加实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 此情,不关风月
- 下一篇: 宠物市场前景受关注 龙头企业纷纷入局争夺