執行存儲過程sql
using System; using System.Data; using System.Configuration; using System.Data.SqlClient; /// <summary> /// Summary description for BaseDB /// </summary> public class BaseDB { #region 相關數據庫訪問成員變量定義 /// <summary> /// 數據庫鏈接對象 /// </summary> public SqlConnection conn = null; /// <summary> /// 命令操做 /// </summary> private SqlCommand m_Command = null; /// <summary> /// 異常錯誤標示 /// 0 無異常 1 嚴重異常 2 通常性異常,能夠繼續執行 /// </summary> public byte m_nExpErrorFlag = 0; /// <summary> /// 內部錯誤 /// </summary> public string m_InnerError = ""; /// <summary> /// 外部錯誤 /// </summary> public string m_OutError = "對不起,數據庫操做異常,請將錯誤即時報告給咱們。"; #endregion #region BaseDB /// <summary> /// 構造數據庫鏈接 /// </summary> /// <param name="strConnectString">數據庫鏈接語句</param> public BaseDB(string strConnectString) { if (conn == null) conn = new SqlConnection(strConnectString); if (conn.State != ConnectionState.Open) { int nCount = 0; while (nCount < 5) { try { nCount++; conn.Open(); if (conn.State == ConnectionState.Open) break; } catch (Exception exp) { nCount++; m_nExpErrorFlag = 1; m_InnerError = "錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; SystemError.CreateErrorLog(m_InnerError); } } } } public BaseDB() { } #endregion #region 相關方法定義 #region CreateCommand /// <summary> /// 建立使用存儲過程的操做命令對象 /// </summary> /// <param name="procName">過程名</param> /// <param name="prams">參數集</param> /// <returns>返回值</returns> private SqlCommand CreateCommand(string procName, SqlParameter[] prams) { //建立數據庫操做 if (m_Command == null) m_Command = new SqlCommand(procName, conn); else m_Command.CommandText = procName; m_Command.CommandType = CommandType.StoredProcedure; m_Command.Parameters.Clear();//清除參數 // add proc parameters if (prams != null) { foreach (SqlParameter parameter in prams) m_Command.Parameters.Add(parameter); } // return param 此處暫時可不要 /*m_Command.Parameters.Add( new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); */ return m_Command; } #endregion #region RunProc /// <summary> /// 運行存儲過程 /// </summary> /// <param name="procName">過程名</param> /// <param name="prams">參數集</param> /// <returns>返回過程的返回值</returns> public int RunProc(string strProcName, SqlParameter[] prams) { m_nExpErrorFlag = 0; SqlCommand myCommand; try { myCommand = CreateCommand(strProcName, prams); myCommand.ExecuteNonQuery(); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; if (prams != null) { foreach (SqlParameter parameter in prams) { if (parameter.SqlDbType == SqlDbType.Int || parameter.SqlDbType == SqlDbType.BigInt || parameter.SqlDbType == SqlDbType.Decimal) { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=" + parameter.Value + ",Direction." + parameter.Direction; } else { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=\"" + parameter.Value + "\",Direction." + parameter.Direction; } } } SystemError.CreateErrorLog(m_InnerError); return -9; } conn.Close(); return (int)myCommand.Parameters["@ReturnValue"].Value; } #endregion #region RunProcDT /// <summary> /// 運行存儲過程,返回DataTable,用於查詢類存儲過程的操做 /// </summary> /// <param name="procName">過程名</param> public DataTable RunProcDT(string strProcName) { m_nExpErrorFlag = 0; SqlCommand myCommand; SqlDataAdapter dataAdapter; DataTable dtResult; try { myCommand = CreateCommand(strProcName, null); dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = myCommand; dtResult = new DataTable(); dataAdapter.Fill(dtResult); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return dtResult; } /// <summary> /// 運行存儲過程,返回DataTable /// </summary> /// <param name="procName">過程名</param> /// <param name="prams">參數集</param> /// <param name="strDataTableName">表別名</param> public DataTable RunProcDT(string strProcName, SqlParameter[] prams) { m_nExpErrorFlag = 0; SqlCommand myCommand; SqlDataAdapter dataAdapter; DataTable dtResult; try { myCommand = CreateCommand(strProcName, prams); dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = myCommand; dtResult = new DataTable(); dataAdapter.Fill(dtResult); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; if (prams != null) { foreach (SqlParameter parameter in prams) { if (parameter.SqlDbType == SqlDbType.Int || parameter.SqlDbType == SqlDbType.BigInt || parameter.SqlDbType == SqlDbType.Decimal) { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=" + parameter.Value + ",Direction." + parameter.Direction; } else { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=\"" + parameter.Value + "\",Direction." + parameter.Direction; } } } SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return dtResult; } /// <summary> /// 運行存儲過程,返回DataTable,用於查詢類存儲過程的操做 /// </summary> /// <param name="procName">過程名</param> /// <param name="strDataTableName">表別名</param> public DataTable RunProcDT(string strProcName, string strDataTableName) { m_nExpErrorFlag = 0; SqlCommand myCommand; SqlDataAdapter dataAdapter; DataTable dtResult; try { myCommand = CreateCommand(strProcName, null); dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = myCommand; dtResult = new DataTable(); dtResult.TableName = strDataTableName; dataAdapter.Fill(dtResult); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return dtResult; } /// <summary> /// 運行存儲過程,返回DataTable /// </summary> /// <param name="procName">過程名</param> /// <param name="prams">參數集</param> /// <param name="strDataTableName">表別名</param> public DataTable RunProcDT(string strProcName, SqlParameter[] prams, string strDataTableName) { m_nExpErrorFlag = 0; SqlCommand myCommand; SqlDataAdapter dataAdapter; DataTable dtResult; try { myCommand = CreateCommand(strProcName, prams); dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = myCommand; dtResult = new DataTable(); dtResult.TableName = strDataTableName; dataAdapter.Fill(dtResult); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; if (prams != null) { foreach (SqlParameter parameter in prams) { if (parameter.SqlDbType == SqlDbType.Int || parameter.SqlDbType == SqlDbType.BigInt || parameter.SqlDbType == SqlDbType.Decimal) { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=" + parameter.Value + ",Direction." + parameter.Direction; } else { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=\"" + parameter.Value + "\",Direction." + parameter.Direction; } } } SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return dtResult; } #endregion #region RunProcScalar /// <summary> /// 運行存儲過程,返回第一行第一列,用於查詢類存儲過程的操做 /// </summary> /// <param name="procName">過程名</param> public object RunProcScalar(string strProcName) { m_nExpErrorFlag = 0; SqlCommand myCommand; object o; try { myCommand = CreateCommand(strProcName, null); o = myCommand.ExecuteScalar(); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return o; } /// <summary> /// 運行存儲過程,返回第一行第一列,用於查詢類存儲過程的操做 /// </summary> /// <param name="procName">過程名</param> public object RunProcScalar(string strProcName, SqlParameter[] prams) { m_nExpErrorFlag = 0; SqlCommand myCommand; object o; try { myCommand = CreateCommand(strProcName, prams); o = myCommand.ExecuteScalar(); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; if (prams != null) { foreach (SqlParameter parameter in prams) { if (parameter.SqlDbType == SqlDbType.Int || parameter.SqlDbType == SqlDbType.BigInt || parameter.SqlDbType == SqlDbType.Decimal) { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=" + parameter.Value + ",Direction." + parameter.Direction; } else { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=\"" + parameter.Value + "\",Direction." + parameter.Direction; } } } SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return o; } #endregion #region RunProcDS /// <summary> /// 運行存儲過程,返回DataSet,用於查詢類存儲過程的操做 /// </summary> /// <param name="procName">過程名</param> public DataSet RunProcDS(string strProcName) { m_nExpErrorFlag = 0; SqlCommand myCommand; SqlDataAdapter dataAdapter; DataSet dsResult; try { myCommand = CreateCommand(strProcName, null); dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = myCommand; dsResult = new DataSet(); dataAdapter.Fill(dsResult); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return dsResult; } /// <summary> /// 運行存儲過程,返回DataSet /// </summary> /// <param name="procName">過程名</param> /// <param name="prams">參數集</param> /// <param name="strDataTableName">表別名</param> public DataSet RunProcDS(string strProcName, SqlParameter[] prams) { m_nExpErrorFlag = 0; SqlCommand myCommand; SqlDataAdapter dataAdapter; DataSet dsResult; try { myCommand = CreateCommand(strProcName, prams); dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = myCommand; dsResult = new DataSet(); dataAdapter.Fill(dsResult); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + " 異常消息:" + exp.Message; if (prams != null) { foreach (SqlParameter parameter in prams) { if (parameter.SqlDbType == SqlDbType.Int || parameter.SqlDbType == SqlDbType.BigInt || parameter.SqlDbType == SqlDbType.Decimal) { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=" + parameter.Value + ",Direction." + parameter.Direction; } else { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=\"" + parameter.Value + "\",Direction." + parameter.Direction; } } } SystemError.CreateErrorLog(m_InnerError); return null; } conn.Close(); return dsResult; } #endregion #region RunProcReader /// <summary> /// 運行存儲過程,返回SqlDataReader(使用完須關閉SqlDataReader,釋放使用SqlDataReader資源) /// </summary> /// <param name="strProcName">過程名</param> /// <returns></returns> public SqlDataReader RunProcReader(string strProcName) { m_nExpErrorFlag = 0; SqlDataReader myReader; SqlCommand myCommand; try { myCommand = CreateCommand(strProcName, null); myReader = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + "異常消息:" + exp.Message; SystemError.CreateErrorLog(m_InnerError); return null; } return myReader; } /// <summary> /// 運行存儲過程,返回SqlDataReader(使用完須關閉SqlDataReader,釋放使用SqlDataReader資源) /// </summary> /// <param name="strProcName">過程名</param> /// <param name="prams">參數集</param> /// <returns></returns> public SqlDataReader RunProcReader(string strProcName, SqlParameter[] prams) { m_nExpErrorFlag = 0; SqlDataReader myReader; SqlCommand myCommand; try { myCommand = CreateCommand(strProcName, prams); myReader = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection); } catch (Exception exp) { m_nExpErrorFlag = 1; m_InnerError = "存儲過程名:" + strProcName + " 錯誤對象名:" + exp.Source + "異常消息:" + exp.Message; if (prams != null) { foreach (SqlParameter parameter in prams) { if (parameter.SqlDbType == SqlDbType.Int || parameter.SqlDbType == SqlDbType.BigInt || parameter.SqlDbType == SqlDbType.Decimal) { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=" + parameter.Value + ",Direction." + parameter.Direction; } else { m_InnerError = m_InnerError + "\r\n" + parameter.ParameterName + "=\"" + parameter.Value + "\",Direction." + parameter.Direction; } } } SystemError.CreateErrorLog(m_InnerError); return null; } return myReader; } #endregion #region GetDataSet public DataSet GetDataSet(string sql) { SqlDataAdapter sda = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); sda.Fill(ds); if (conn.State != ConnectionState.Closed) conn.Close(); return ds; } #endregion #region 針對SqlParameters的一些構造模塊 /// <summary> /// 構建存儲過程調用參數 /// </summary> /// <param name="ParamName">存儲過程名稱</param> /// <param name="Direction">傳入仍是傳出</param> /// <param name="Value">參數值</param> /// <returns>返回SqlParameter對象</returns> private SqlParameter MakeParam(string ParamName, ParameterDirection Direction, object Value) { SqlParameter param = new SqlParameter(); param.ParameterName = ParamName; param.Direction = Direction; if (!(Direction == ParameterDirection.Output && Value == null)) param.Value = Value; return param; } /// <summary> /// /// </summary> /// <param name="paramName"></param> /// <param name="Direction"></param> /// <param name="Type"></param> /// <param name="Size"></param> /// <param name="Value"></param> /// <returns></returns> private SqlParameter MakeParam(string paramName, ParameterDirection Direction, SqlDbType Type, int Size, object Value) { SqlParameter param = new SqlParameter(paramName, Type, Size); param.Direction = Direction; if (!(Direction == ParameterDirection.Output && Value == null)) param.Value = Value; return param; } /// <summary> /// 構建存儲過程傳入參數 /// </summary> /// <param name="ParamName">存儲過程名稱</param> /// <param name="Value">參數值</param> /// <returns>返回SqlParameter對象</returns> public SqlParameter MakeInParam(string ParamName, object Value) { return MakeParam(ParamName, ParameterDirection.Input, Value); } /// <summary> /// /// </summary> /// <param name="ParamName"></param> /// <param name="Type"></param> /// <param name="Size"></param> /// <param name="Value"></param> /// <returns></returns> public SqlParameter MakeInParam(string ParamName, SqlDbType Type, int Size, object Value) { return MakeParam(ParamName, ParameterDirection.Input, Type, Size, Value); } /// <summary> /// 構建存儲過程 /// </summary> /// <param name="ParamName">存儲過程名稱</param> /// <param name="Value">參數值</param> /// <returns>返回SqlParameter對象</returns> public SqlParameter MakeReturnParam(string ParamName) { return MakeParam(ParamName, ParameterDirection.ReturnValue, null); } /// <summary> /// /// </summary> /// <param name="ParamName"></param> /// <param name="Type"></param> /// <param name="Size"></param> /// <param name="Value"></param> /// <returns></returns> public SqlParameter MakeReturnParam(string ParamName, SqlDbType Type, int Size) { return MakeParam(ParamName, ParameterDirection.ReturnValue, Type, Size, null); } /// <summary> /// 構建存儲過程傳出參數 /// </summary> /// <param name="ParamName">存儲過程名稱</param> /// <returns>返回SqlParameter對象</returns> public SqlParameter MakeOutParam(string ParamName) { return MakeParam(ParamName, ParameterDirection.Output, null); } /// <summary> /// /// </summary> /// <param name="ParamName"></param> /// <param name="Type"></param> /// <param name="Size"></param> /// <returns></returns> public SqlParameter MakeOutParam(string ParamName, SqlDbType Type, int Size) { return MakeParam(ParamName, ParameterDirection.Output, Type, Size, null); } #endregion #endregion }
快捷生成SqlParameter數組數據庫
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace DataAccess { /// <summary> /// 存儲過程相關工具類 /// </summary> public class ProcHelper { #region 快捷生成一個 SqlParameter 數組 /// <summary> /// 快捷生成一個 SqlParameter 數組 /// </summary> /// <param name="paramArr">參數信息 /// 格式要求:參數名 類型(長度) 參數類型(in/out/inout/return), [若是前一個參數是輸入參數那麼這個參數是前一個參數的值],參數名 類型(長度) 參數類型(in/out/inout/return),... /// 例:"id int(4) in", 1, "name varchar(20) out" /// 上述參數表示將建立兩個 SqlParameter 對象 name 分別爲 @id 和 @name,@ 可省略不寫 /// 1 爲名爲 @id 的輸入參數即 SqlParameter 對象的 Value 屬性值 /// </param> /// <returns>返回生成的參數列表</returns> public static SqlParameter[] GenParams(params object[] paramArr) { var sqlParameters = new List<SqlParameter>(); bool isInDirection = false; // 記錄上一個循環元素是不是輸入參數 int currentLoopParamIndex = -1; // 記錄上一個參數的索引 foreach (var param in paramArr) { // 若是上一個元素是輸入參數,那麼將後面一個元素賦值給上一個參數的 Value 屬性 if (isInDirection) { sqlParameters.ToArray()[currentLoopParamIndex].Value = param; isInDirection = false; continue; } bool isParamInfo = param.GetType().Name.ToLower() == "string"; if (isParamInfo && !isInDirection) { try { var strs = param.ToString().Split(' '); string paramName = strs[0].Contains("@") ? strs[0] : "@" + strs[0]; string[] dataTypeArr = strs[1].Split('('); string dataTypeStr = dataTypeArr[0]; int dataLength = Convert.ToInt32(dataTypeArr[1].Replace(")", "")); string directionStr = strs[2]; SqlParameter sqlParameter = new SqlParameter(paramName, GetDataType(dataTypeStr), dataLength); sqlParameter.Direction = GetDirection(directionStr); isInDirection = sqlParameter.Direction == ParameterDirection.Input; sqlParameters.Add(sqlParameter); currentLoopParamIndex++; } catch (Exception e) { throw new Exception("[" + param + "]參數格式不正確"); } } } return sqlParameters.ToArray(); } #endregion #region 經過字符串獲取參數對應數據類型的枚舉 private static SqlDbType GetDataType(string dataTypeStr) { dataTypeStr = dataTypeStr.ToLower(); int typeCode = -1; switch (dataTypeStr) { case "bigint": typeCode = 0; break; case "binary": typeCode = 1; break; case "bit": typeCode = 2; break; case "char": typeCode = 3; break; case "datatime": typeCode = 4; break; case "decimal": typeCode = 5; break; case "float": typeCode = 6; break; case "image": typeCode = 7; break; case "int": typeCode = 8; break; case "money": typeCode = 9; break; case "nchar": typeCode = 10; break; case "ntext": typeCode = 11; break; case "nvarchar": typeCode = 12; break; case "real": typeCode = 13; break; case "uniqueidentifier": typeCode = 14; break; case "smalldatatime": typeCode = 15; break; case "smallint": typeCode = 16; break; case "smallmoney": typeCode = 17; break; case "text": typeCode = 18; break; case "timestamp": typeCode = 19; break; case "tinyint": typeCode = 20; break; case "varbinary": typeCode = 21; break; case "varchar": typeCode = 22; break; case "variant": typeCode = 23; break; case "xml": typeCode = 25; break; case "udt": typeCode = 29; break; case "structured": typeCode = 30; break; case "date": typeCode = 31; break; case "time": typeCode = 32; break; case "datatime2": typeCode = 33; break; case "datetimeoffset": typeCode = 34; break; } if (typeCode == -1) throw new Exception("無此數據類型[" + dataTypeStr + "]"); return (SqlDbType) typeCode; } #endregion #region 經過字符串獲取參數輸出類型 private static ParameterDirection GetDirection(string directionStr) { int directionCode = -1; switch (directionStr) { case "in": directionCode = 1; break; case "out": directionCode = 2; break; case "inout": directionCode = 3; break; case "return": directionCode = 6; break; } if (directionCode == -1) throw new Exception("無此輸出類型[" + directionStr + "]"); return (ParameterDirection) directionCode; } #endregion } }