using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;
using System.Text;
using System.Configuration;
namespace GoEngine
{
public class Filed
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private object value;
public object Value
{
get { return this.value; }
set { this.value = value; }
}
public Filed(string Name, dynamic Value)
{
this.Name = Name;
this.Value = Value;
}
}
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
/// common uses of SqlClient
///入口安全比ORM不差,没有了结构体可以自由开发
///外部不能直接调用 ExecuteNonQuery
///太复杂了,更换数据库,限制防止多的没用的东西。性能肯定就差点儿。
///脱裤子放一次屁,比ORM性能差点儿???未必
///操作数据库的语句都得是参数化的,查询数据库的单管
///低耦合 结构化就高度耦合了 性能最高
///每次查询只能是单条的语句不能包括没用的信息
///if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
///throw new Exception("只能查询,不能执行非法语句");
/name=@name 正则查找很费时间而且也不匹配。
/// </summary>
public sealed class SqlHelper
{
private static readonly string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
private static readonly string tablefix = ConfigurationManager.AppSettings["tablefix"];
#region 扩展
public static void Insert(string TableName, Filed[] Fileds)
{
Insert(null, TableName, Fileds);
}
public static void Update(string TableName, int ID, Filed[] Fileds)
{
Update(null, TableName, ID, Fileds);
}
public static void Update(string TableName, Filed[] Condition, Filed[] Fileds)
{
Update(null, TableName, Condition, Fileds);
}
public static void Delete(string TableName, int ID)
{
Update(null, TableName, ID, null);
}
public static void Insert(IDbTransaction tran, string TableName, Filed[] Fileds)
{
ExecuteNonQuery(CommandType.Text, InsertSql(TableName, Fileds), ConvertToSqlParameters(Fileds));
}
public static void Update(IDbTransaction tran, string TableName, int ID, Filed[] Fileds)
{
Filed[] Condition = new Filed[1];
Condition[0] = new Filed("id", ID);
ExecuteNonQuery(CommandType.Text, UpdateSql(TableName, Fileds, Condition), ConvertToSqlParameters(Fileds));
}
public static void Update(IDbTransaction tran, string TableName, Filed[] Fileds, Filed[] Condition)
{
ExecuteNonQuery(CommandType.Text, UpdateSql(TableName, Fileds, Condition), ConvertToSqlParameters(Fileds, Condition));
}
public static void Delete(IDbTransaction tran, string TableName, int ID)
{
Filed[] Condition = new Filed[1];
Condition[0] = new Filed("id", ID);
ExecuteNonQuery(CommandType.Text, DeleteSql(TableName, Condition), ConvertToSqlParameters(Condition));
}
public static void Delete(IDbTransaction tran, string TableName, Filed[] Condition)
{
ExecuteNonQuery(CommandType.Text, DeleteSql(TableName, Condition), ConvertToSqlParameters(Condition));
}
private static string InsertSql(string TableName, Filed[] Fileds)
{
StringBuilder strcol = new StringBuilder();
StringBuilder strvalue = new StringBuilder();
foreach (Filed f in Fileds)
{
strcol.Append(f.Name + ",");
strvalue.Append("@" + f.Name + ",");
}
return "INSERT INTO [" + tablefix + TableName + "] (" + strcol.ToString().TrimEnd(',') + ")values(" + strvalue.ToString().TrimEnd(',') + ")";
}
private static string UpdateSql(string TableName, Filed[] Fileds, Filed[] Condition)
{
StringBuilder strset = new StringBuilder();
StringBuilder strcondition = new StringBuilder();
foreach (Filed f in Fileds)
{
strset.Append(f.Name + "=@" + f.Name + ",");
}
foreach (Filed f in Condition)
{
strcondition.Append(" AND " + f.Name + "=@" + f.Name + ",");
}
return "UPDATE [" + tablefix + TableName + "] SET " + strset.ToString().TrimEnd(',') + " WHERE 1=1 " + strcondition.ToString().TrimEnd(',');
}
private static string DeleteSql(string TableName, Filed[] Condition)
{
StringBuilder strcondition = new StringBuilder();
foreach (Filed f in Condition)
{
strcondition.Append(" AND " + f.Name + "=@" + f.Name + ",");
}
return "DELETE FROM [" + tablefix + TableName + "] WHERE 1=1 " + strcondition.ToString().TrimEnd(',');
}
private static SqlParameter[] ConvertToSqlParameters(Filed[] Fileds)
{
SqlParameter[] commandParameters = null;
if (Fileds != null)
{
commandParameters = new SqlParameter[Fileds.Length];
int i = 0;
foreach (Filed f in Fileds)
{
commandParameters[i] = new SqlParameter("@" + f.Name, f.Value);
i++;
}
}
return commandParameters;
}
private static SqlParameter[] ConvertToSqlParameters(Filed[] Fileds, Filed[] Condition)
{
SqlParameter[] commandParameters = null;
int i = 0;
commandParameters = new SqlParameter[Fileds.Length + Condition.Length];
if (Fileds != null)
{
foreach (Filed f in Fileds)
{
commandParameters[i] = new SqlParameter("@" + f.Name, f.Value);
i++;
}
}
if (Condition != null)
{
foreach (Filed f in Condition)
{
commandParameters[i] = new SqlParameter("@" + f.Name, f.Value);
i++;
}
}
return commandParameters;
}
#endregion
#region private utility methods & constructors
// Since this class provides only static methods, make the default constructor private to prevent
// instances from being created with "new SqlHelper()"
private SqlHelper() { }
/// <summary>
/// This method is used to attach array of SqlParameters to a SqlCommand.
///
/// This method will assign a value of DbNull to any parameter with a direction of
/// InputOutput and a value of null.
///
/// This behavior will prevent default values from being used, but
/// this will be the less common case than an intended pure output parameter (derived as InputOutput)
/// where the user provided no input value.
/// </summary>
/// <param name="command">The command to which the parameters will be added</param>
/// <param name="commandParameters">An array of SqlParameters to be added to command</param>
private static void AttachParameters(SqlCommand command, params object[] commandParameters)
{
if (command == null) throw new ArgumentNullException("command");
if (commandParameters != null)
{
bool isallSqlParameter = true;
foreach (object o in commandParameters)
{
if (!(o is SqlParameter))
{
isallSqlParameter = false;
}
}
if (isallSqlParameter)
{
foreach (SqlParameter p in commandParameters)
{
if (p != null)
{
// Check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput ||
p.Direction == ParameterDirection.Input) &&
(p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
}
else
{
int p = 0;
foreach (object o in commandParameters)
{
if (o == null)
{
command.Parameters.Add(new SqlParameter("@p" + p.ToString(), DBNull.Value));
}
else
{
command.Parameters.Add(new SqlParameter("@p" + p.ToString(), o));
}
p++;
}
}
}
}
/// <summary>
/// This method assigns an array of values to an array of SqlParameters
/// </summary>
/// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
/// <param name="parameterValues">Array of objects holding the values to be assigned</param>
private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters == null) || (parameterValues == null))
{
// Do nothing if we get no data
return;
}
// We must have the same number of values as we pave parameters to put them in
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
// Iterate through the SqlParameters, assigning the values from the corresponding position in the
// value array
for (int i = 0, j = commandParameters.Length; i < j; i++)
{
// If the current array value derives from IDbDataParameter, then assign its Value property
if (parameterValues[i] is IDbDataParameter)
{
IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
if (paramInstance.Value == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = paramInstance.Value;
}
}
else if (parameterValues[i] == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = parameterValues[i];
}
}
}
/// <summary>
/// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
/// to the provided command
/// </summary>
/// <param name="command">The SqlCommand to be prepared</param>
/// <param name="connection">A valid SqlConnection, on which to execute this command</param>
/// <param name="transaction">A valid SqlTransaction, or 'null'</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
/// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, out bool mustCloseConnection, params object[] parameterValues)
{
if (command == null) throw new ArgumentNullException("command");
if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
// If the provided connection is not open, we will open it
if (connection.State != ConnectionState.Open)
{
mustCloseConnection = true;
connection.Open();
}
else
{
mustCloseConnection = false;
}
// Associate the connection with the command
command.Connection = connection;
// Set the command text (stored procedure name or SQL statement)
command.CommandText = commandText;
// If we were provided a transaction, assign it
if (transaction != null)
{
if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
command.Transaction = transaction;
}
// Set the command type
command.CommandType = commandType;
// Attach the command parameters if they are provided
if ((parameterValues != null) && (parameterValues.Length > 0))
{
AttachParameters(command, parameterValues);
Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
//SqlParameter[] commandParameters = SqlHelperParameterCache.GetCachedParameterSet(connectionString, commandText);
//if (commandParameters != null)
//{
// // Assign the provided values to these parameters based on parameter order
// AssignParameterValues(commandParameters, parameterValues);
//}
//else
//{
// AttachParameters(command, parameterValues);
// SqlHelperParameterCache.CacheParameterSet(connectionString, commandText, command.Parameters);
//}
}
return;
}
#endregion private utility methods & constructors
#region ExecuteNonQuery
private static int ExecuteNonQuery(string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(CommandType.Text, commandText, null);
}
private static int ExecuteNonQuery(string commandText, params object[] commandParameters)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(CommandType.Text, commandText, commandParameters);
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
/// the connection string
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
private static int ExecuteNonQuery(CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
/// using the provided parameters
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
private static int ExecuteNonQuery(CommandType commandType, string commandText, params object[] commandParameters)
{
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
// Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takes a connection in place of the connection string
return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
}
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
private static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(connection, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
private static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params object[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, out mustCloseConnection, commandParameters);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
private static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(transaction, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
private static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params object[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, out mustCloseConnection, commandParameters);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
#endregion ExecuteNonQuery
#region ExecuteDataSet
public static DataSet ExecuteDataSet(string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataSet(CommandType.Text, commandText, null);
}
public static DataSet ExecuteDataSet(string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataSet(CommandType.Text, commandText, commandParameters);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataSet(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DataSet containing the resultset generated by the command</returns>
public static DataSet ExecuteDataSet(CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataSet(commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataSet(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DataSet containing the resultset generated by the command</returns>
public static DataSet ExecuteDataSet(CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
// Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takes a connection in place of the connection string
return ExecuteDataSet(connection, commandType, commandText, commandParameters);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataSet(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DataSet containing the resultset generated by the command</returns>
private static DataSet ExecuteDataSet(SqlConnection connection, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataSet(connection, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataSet(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DataSet containing the resultset generated by the command</returns>
private static DataSet ExecuteDataSet(SqlConnection connection, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (connection == null) throw new ArgumentNullException("connection");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, out mustCloseConnection, commandParameters);
// Create the DataAdapter & DataSet
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
// Fill the DataSet using default values for DataTable names, etc
da.Fill(ds);
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
// Return the DataSet
return ds;
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataSet(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DataSet containing the resultset generated by the command</returns>
public static DataSet ExecuteDataSet(SqlTransaction transaction, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataSet(transaction, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataSet(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DataSet containing the resultset generated by the command</returns>
public static DataSet ExecuteDataSet(SqlTransaction transaction, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, out mustCloseConnection, commandParameters);
// Create the DataAdapter & DataSet
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
// Fill the DataSet using default values for DataTable names, etc
da.Fill(ds);
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
// Return the DataSet
return ds;
}
}
#endregion ExecuteDataSet
#region ExecuteReader
/// <summary>
/// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
/// we can set the appropriate CommandBehavior when calling ExecuteReader()
/// </summary>
private enum SqlConnectionOwnership
{
/// <summary>Connection is owned and managed by SqlHelper</summary>
Internal,
/// <summary>Connection is owned and managed by the caller</summary>
External
}
/// <summary>
/// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
/// </summary>
/// <remarks>
/// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
///
/// If the caller provided the connection, we want to leave it to them to manage.
/// </remarks>
/// <param name="connection">A valid SqlConnection, on which to execute this command</param>
/// <param name="transaction">A valid SqlTransaction, or 'null'</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
/// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
/// <returns>SqlDataReader containing the results of the command</returns>
private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlConnectionOwnership connectionOwnership, params object[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection");
bool mustCloseConnection = false;
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, transaction, commandType, commandText, out mustCloseConnection, commandParameters);
// Create a reader
SqlDataReader dataReader;
// Call ExecuteReader with the appropriate CommandBehavior
if (connectionOwnership == SqlConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
// Detach the SqlParameters from the command object, so they can be used again.
// HACK: There is a problem here, the output parameter values are fletched
// when the reader is closed, so if the parameters are detached from the command
// then the SqlReader can磘 set its values.
// When this happen, the parameters can磘 be used again in other command.
bool canClear = true;
foreach (SqlParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
canClear = false;
}
if (canClear)
{
cmd.Parameters.Clear();
}
return dataReader;
}
catch
{
if (mustCloseConnection)
connection.Close();
throw;
}
}
public static SqlDataReader ExecuteReader(string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(CommandType.Text, commandText, commandParameters);
}
public static SqlDataReader ExecuteReader(string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(CommandType.Text, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open();
// Call the private overload that takes an internally owned connection in place of the connection string
return ExecuteReader(connection, null, commandType, commandText, SqlConnectionOwnership.Internal, commandParameters);
}
catch
{
// If we fail to return the SqlDatReader, we need to close the connection ourselves
if (connection != null) connection.Close();
throw;
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
private static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(connection, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
private static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call to the private overload using a null transaction value and an externally owned connection
return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, SqlConnectionOwnership.External, commandParameters);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(transaction, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Pass through to private overload, indicating that the connection is owned by the caller
return ExecuteReader(transaction.Connection, transaction, commandType, commandText, SqlConnectionOwnership.External, commandParameters);
}
#endregion ExecuteReader
#region ExecuteScalar
public static object ExecuteScalar(string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(CommandType.Text, commandText, null);
}
public static object ExecuteScalar(string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(CommandType.Text, commandText, commandParameters);
}
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
// Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takes a connection in place of the connection string
return ExecuteScalar(connection, commandType, commandText, commandParameters);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
private static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(connection, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
private static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (connection == null) throw new ArgumentNullException("connection");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, out mustCloseConnection, commandParameters);
// Execute the command & return the results
object retval = cmd.ExecuteScalar();
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(transaction, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, out mustCloseConnection, commandParameters);
// Execute the command & return the results
object retval = cmd.ExecuteScalar();
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
#endregion ExecuteScalar
#region ExecuteDataTable 扩展
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// DataTable ds = ExecuteDataTable(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DataTable containing the resultset generated by the command</returns>
public static DataTable ExecuteDataTable(string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataTable(CommandType.Text, commandText, null);
}
public static DataTable ExecuteDataTable(string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataTable(CommandType.Text, commandText, commandParameters);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// DataTable ds = ExecuteDataTable(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DataTable containing the resultset generated by the command</returns>
public static DataTable ExecuteDataTable(CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataTable(commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataTable ds = ExecuteDataTable(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DataTable containing the resultset generated by the command</returns>
public static DataTable ExecuteDataTable(CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
// Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takes a connection in place of the connection string
return ExecuteDataTable(connection, commandType, commandText, commandParameters);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// DataTable ds = ExecuteDataTable(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DataTable containing the resultset generated by the command</returns>
private static DataTable ExecuteDataTable(SqlConnection connection, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataTable(connection, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataTable ds = ExecuteDataTable(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DataTable containing the resultset generated by the command</returns>
private static DataTable ExecuteDataTable(SqlConnection connection, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (connection == null) throw new ArgumentNullException("connection");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, out mustCloseConnection, commandParameters);
// Create the DataAdapter & DataTable
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable ds = new DataTable();
// Fill the DataTable using default values for DataTable names, etc
da.Fill(ds);
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
// Return the DataTable
return ds;
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DataTable ds = ExecuteDataTable(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DataTable containing the resultset generated by the command</returns>
public static DataTable ExecuteDataTable(SqlTransaction transaction, CommandType commandType, string commandText)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataTable(transaction, commandType, commandText, null);
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataTable ds = ExecuteDataTable(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DataTable containing the resultset generated by the command</returns>
public static DataTable ExecuteDataTable(SqlTransaction transaction, CommandType commandType, string commandText, params object[] commandParameters)
{
if (commandText.Contains("@@") || commandText.Contains(";") || commandText.Contains("update") || commandText.Contains("delete") || commandText.Contains("insert"))
throw new Exception("只能查询,不能执行非法语句");
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, out mustCloseConnection, commandParameters);
// Create the DataAdapter & DataTable
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable ds = new DataTable();
// Fill the DataTable using default values for DataTable names, etc
da.Fill(ds);
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
// Return the DataTable
return ds;
}
}
#endregion ExecuteDataTable
}
/// <summary>
/// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
/// ability to discover parameters for stored procedures at run-time.
/// </summary>
public sealed class SqlHelperParameterCache
{
#region private methods, variables, and constructors
//Since this class provides only static methods, make the default constructor private to prevent
//instances from being created with "new SqlHelperParameterCache()"
private SqlHelperParameterCache() { }
private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Deep copy of cached SqlParameter array
/// </summary>
/// <param name="originalParameters"></param>
/// <returns></returns>
private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];
for (int i = 0, j = originalParameters.Length; i < j; i++)
{
clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
}
return clonedParameters;
}
#endregion private methods, variables, and constructors
#region caching functions
/// <summary>
/// Add parameter array to the cache
/// </summary>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters to be cached</param>
public static void CacheParameterSet(string connectionString, string commandText, params object[] commandParameters)
{
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
string hashKey = connectionString + ":" + commandText;
paramCache[hashKey] = commandParameters;
}
/// <summary>
/// Retrieve a parameter array from the cache
/// </summary>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An array of SqlParamters</returns>
public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
{
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
string hashKey = connectionString + ":" + commandText;
SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[];
if (cachedParameters == null)
{
return null;
}
else
{
return CloneParameters(cachedParameters);
}
}
#endregion caching functions
}
}