程序人生: 2005--4-28 于清华档案馆
调用时如下:
///
1<param name="newTreeView"/>
树型控件名称
///
1<param name="TreeViewName"/>
一层的功能名称
///
1<param name="TableName"/>
数据库中的表名
///
1<param name="ParentNameField"/>
父节点的字段名
///
1<param name="CurrentNameField"/>
节点的字段名
///
1<param name="CurrentDataField"/>
节点的数据
newTreeInfoBll.InitTreeData(this.treeView1,"系统业务表","T_S_SystemTableIndex","pid000","name00","id0000");
有什么不懂的或不明白的地方请大家给我发EMAIL,谢谢,希望大家一起进步
---------------------------------
TREEINFO.CS = 数据控制层
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
///
1<summary>
2/// TreeInfo
3/// 树型初使化数据库的所有信息
4/// 乔高峰 2005-04-26
5/// 功能:实现所有树型的初使化
6/// </summary>
public class TreeInfo
{
// private string PARM_TableName;
///
1<summary>
2/// 取某表的所有数据(缺少表名)
3/// </summary>
private string SQL_SELECT_TREE = "SELECT * FROM ";
///
1<summary>
2/// 保存结果的数据集
3/// scf
4/// </summary>
private DataSet newDataSet;
///
1<summary>
2/// 为过滤方便的视图
3/// </summary>
private DataView newDataView;
///
1<summary>
2/// 无参数的构造函数
3/// </summary>
public TreeInfo()
{
}
///
1<summary>
2/// 初使化树型
3/// 乔高峰 2005-04-28
4/// </summary>
///
1<param name="newTreeView"/>
树型控件名称
///
1<param name="TreeViewName"/>
一层的功能名称
///
1<param name="TableName"/>
数据库中的表名
///
1<param name="ParentNameField"/>
父节点的字段名
///
1<param name="CurrentNameField"/>
节点的字段名
///
1<param name="CurrentDataField"/>
节点的数据
public void InitTreeData(TreeView newTreeView,string TreeViewName,string TableName,string ParentNameField,string CurrentNameField,string CurrentDataField)
{
//增加第一层节点的名称,为该树的功能名称
TreeNode newTreeViewName = new TreeNode();
//设置该节点的显示文本
newTreeViewName.Text = TreeViewName;
////树型的图标
//newTreeViewName.ImageIndex = ;
////选择时的图标
//newTreeViewName.SelectedImageIndex = ;
newTreeView.Nodes.Add(newTreeViewName);
//增加第二层数据库里最高层的数据
//从数据库中取数据
try
{
this.newDataSet = new DataSet();
this.SQL_SELECT_TREE = this.SQL_SELECT_TREE + TableName;
SqlHelper.FillDataset(SqlHelper.CONN_STRING,CommandType.Text,this.SQL_SELECT_TREE,this.newDataSet,new string[] {TableName});
this.newDataView = new DataView();
this.newDataView.Table = this.newDataSet.Tables[TableName];
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
CreateTreeNodes(newTreeViewName,ParentNameField,"0",CurrentNameField,CurrentDataField);
}
///
1<summary>
2/// 用递归的方法,生成树型
3/// 乔高峰 2005-04-28
4/// </summary>
///
1<param name="newTreeViewName"/>
一层的节点索引
///
1<param name="ParentNameField"/>
父节点的字段名
///
1<param name="ParentNameValue"/>
父节点的字段值
///
1<param name="CurrentNameField"/>
节点的字段名
///
1<param name="CurrentDataField"/>
节点的数据
public void CreateTreeNodes(TreeNode newTreeViewName,string ParentNameField,string ParentNameValue,string CurrentNameField,string CurrentDataField)
{
try
{
//规定父节点为0的为第一层节点
this.newDataView.RowFilter = ParentNameField + " = '" + ParentNameValue+"'";
//判断是否有记录
if (this.newDataView.Count != 0)
{
//MessageBox.Show(this.newDataView.Count.ToString()+ "运行");
//递归运算
foreach(DataRowView newDataRowView in this.newDataView)
{
//在循环外有一条这个语句
//这条语句是为了找回递归时动态失去的数据
this.newDataView.RowFilter = ParentNameField + " = '" + ParentNameValue+"'";
//新增一个节点
TreeNode newTreeNode = new TreeNode();
//设置该节点的显示文本
newTreeNode.Text = newDataRowView[CurrentNameField].ToString().Trim();
//保存该节点的数据 ID
newTreeNode.Tag = newDataRowView[CurrentDataField].ToString().Trim();
// //树型的图标
// newTreeNode.ImageIndex = ;
// //选择时的图标
// newTreeNode.SelectedImageIndex = ;
//增回节点
newTreeViewName.Nodes.Add(newTreeNode);
//递归运算
CreateTreeNodes(newTreeNode,ParentNameField,newDataRowView[CurrentDataField].ToString().Trim(),CurrentNameField,CurrentDataField);
}
}
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
}
}
-----------------------------------数据访问层----------------------------
//===============================================================================
//数据访问层中最基本的应用程序块(来自微软Microsoft Application Blocks for .NET)
//提供所有有关操作SQL SERVER操作数据库的功能
//乔高峰 2005-04-27
//===============================================================================
using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;
using System.Windows.Forms;
namespace DAL
{
///
1<summary>
2/// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
3/// common uses of SqlClient
4/// </summary>
public sealed class SqlHelper
{
//联接字符串
public static readonly string CONN_STRING = ConfigurationSettings.AppSettings["SQLConnString"] ;
#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()
{
}
///
1<summary>
2/// This method is used to attach array of SqlParameters to a SqlCommand.
3///
4/// This method will assign a value of DbNull to any parameter with a direction of
5/// InputOutput and a value of null.
6///
7/// This behavior will prevent default values from being used, but
8/// this will be the less common case than an intended pure output parameter (derived as InputOutput)
9/// where the user provided no input value.
10/// </summary>
///
1<param name="command"/>
The command to which the parameters will be added
///
1<param name="commandParameters"/>
An array of SqlParameters to be added to command
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
if( command == null ) throw new ArgumentNullException( "command" );
if( commandParameters != null )
{
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);
}
}
}
}
///
1<summary>
2/// This method assigns dataRow column values to an array of SqlParameters
3/// </summary>
///
1<param name="commandParameters"/>
Array of SqlParameters to be assigned values
///
1<param name="dataRow"/>
The dataRow used to hold the stored procedure's parameter values
private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
{
if ((commandParameters == null) || (dataRow == null))
{
// Do nothing if we get no data
return;
}
int i = 0;
// Set the parameters values
foreach(SqlParameter commandParameter in commandParameters)
{
// Check the parameter name
if( commandParameter.ParameterName == null ||
commandParameter.ParameterName.Length <= 1 )
throw new Exception(
string.Format(
"Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
i, commandParameter.ParameterName ) );
if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
i++;
}
}
///
1<summary>
2/// This method assigns an array of values to an array of SqlParameters
3/// </summary>
///
1<param name="commandParameters"/>
Array of SqlParameters to be assigned values
///
1<param name="parameterValues"/>
Array of objects holding the values to be assigned
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];
}
}
}
///
1<summary>
2/// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
3/// to the provided command
4/// </summary>
///
1<param name="command"/>
The SqlCommand to be prepared
///
1<param name="connection"/>
A valid SqlConnection, on which to execute this command
///
1<param name="transaction"/>
A valid SqlTransaction, or 'null'
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParameters to be associated with the command or 'null' if no parameters are required
///
1<param name="mustCloseConnection"/>
1<c>true</c>
if the connection was opened by the method, otherwose is false.
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection )
{
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 (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
return;
}
#endregion private utility methods & constructors
#region ExecuteNonQuery
///
1<summary>
2/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
3/// the connection string
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
4/// </remarks>
///
1<param name="connectionString"/>
A valid connection string for a SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
}
///
1<summary>
2/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
3/// using the provided parameters
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
4/// </remarks>
///
1<param name="connectionString"/>
A valid connection string for a SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParamters used to execute the command
///
1<returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] 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);
}
}
///
1<summary>
2/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
3/// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
4/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
5/// </summary>
///
1<remarks>
2/// This method provides no access to output parameters or the stored procedure's return value parameter.
3///
4/// e.g.:
5/// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
6/// </remarks>
///
1<param name="connectionString"/>
A valid connection string for a SqlConnection
///
1<param name="spName"/>
The name of the stored prcedure
///
1<param name="parameterValues"/>
An array of objects to be assigned as the input values of the stored procedure
///
1<returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
{
if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
// If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
// Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takes an array of SqlParameters
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
}
///
1<summary>
2/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
3/// </summary>
///
1<remarks>
2/// e.g.:
3/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
4/// </remarks>
///
1<param name="connection"/>
A valid SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<returns>An int representing the number of rows affected by the command</returns>
public 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, (SqlParameter[])null);
}
///
1<summary>
2/// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
3/// using the provided parameters.
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
4/// </remarks>
///
1<param name="connection"/>
A valid SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParamters used to execute the command
///
1<returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] 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, commandParameters, out mustCloseConnection );
// 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;
}
///
1<summary>
2/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
3/// using the provided parameter values. This method will query the database to discover the parameters for the
4/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
5/// </summary>
///
1<remarks>
2/// This method provides no access to output parameters or the stored procedure's return value parameter.
3///
4/// e.g.:
5/// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
6/// </remarks>
///
1<param name="connection"/>
A valid SqlConnection
///
1<param name="spName"/>
The name of the stored procedure
///
1<param name="parameterValues"/>
An array of objects to be assigned as the input values of the stored procedure
///
1<returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
{
if( connection == null ) throw new ArgumentNullException( "connection" );
if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
// If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
// Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takes an array of SqlParameters
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
}
///
1<summary>
2/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
3/// </summary>
///
1<remarks>
2/// e.g.:
3/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
4/// </remarks>
///
1<param name="transaction"/>
A valid SqlTransaction
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<returns>An int representing the number of rows affected by the command</returns>
public 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, (SqlParameter[])null);
}
///
1<summary>
2/// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
3/// using the provided parameters.
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
4/// </remarks>
///
1<param name="transaction"/>
A valid SqlTransaction
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParamters used to execute the command
///
1<returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] 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, commandParameters, out mustCloseConnection );
// 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;
}
///
1<summary>
2/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
3/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
4/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
5/// </summary>
///
1<remarks>
2/// This method provides no access to output parameters or the stored procedure's return value parameter.
3///
4/// e.g.:
5/// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
6/// </remarks>
///
1<param name="transaction"/>
A valid SqlTransaction
///
1<param name="spName"/>
The name of the stored procedure
///
1<param name="parameterValues"/>
An array of objects to be assigned as the input values of the stored procedure
///
1<returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
{
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" );
if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
// If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takes an array of SqlParameters
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion ExecuteNonQuery
#region ExecuteDataset
///
1<summary>
2/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
3/// the connection string.
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
4/// </remarks>
///
1<param name="connectionString"/>
A valid connection string for a SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
}
///
1<summary>
2/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
3/// using the provided parameters.
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
4/// </remarks>
///
1<param name="connectionString"/>
A valid connection string for a SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParamters used to execute the command
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] 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 ExecuteDataset(connection, commandType, commandText, commandParameters);
}
}
///
1<summary>
2/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
3/// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
4/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
5/// </summary>
///
1<remarks>
2/// This method provides no access to output parameters or the stored procedure's return value parameter.
3///
4/// e.g.:
5/// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
6/// </remarks>
///
1<param name="connectionString"/>
A valid connection string for a SqlConnection
///
1<param name="spName"/>
The name of the stored procedure
///
1<param name="parameterValues"/>
An array of objects to be assigned as the input values of the stored procedure
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
{
if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
// If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
// Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takes an array of SqlParameters
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
}
///
1<summary>
2/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
3/// </summary>
///
1<remarks>
2/// e.g.:
3/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
4/// </remarks>
///
1<param name="connection"/>
A valid SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
}
///
1<summary>
2/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
3/// using the provided parameters.
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
4/// </remarks>
///
1<param name="connection"/>
A valid SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParamters used to execute the command
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] 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, commandParameters, out mustCloseConnection );
// 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;
}
}
///
1<summary>
2/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
3/// using the provided parameter values. This method will query the database to discover the parameters for the
4/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
5/// </summary>
///
1<remarks>
2/// This method provides no access to output parameters or the stored procedure's return value parameter.
3///
4/// e.g.:
5/// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
6/// </remarks>
///
1<param name="connection"/>
A valid SqlConnection
///
1<param name="spName"/>
The name of the stored procedure
///
1<param name="parameterValues"/>
An array of objects to be assigned as the input values of the stored procedure
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
{
if( connection == null ) throw new ArgumentNullException( "connection" );
if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
// If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
// Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takes an array of SqlParameters
return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
}
///
1<summary>
2/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
3/// </summary>
///
1<remarks>
2/// e.g.:
3/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
4/// </remarks>
///
1<param name="transaction"/>
A valid SqlTransaction
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
}
///
1<summary>
2/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
3/// using the provided parameters.
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
4/// </remarks>
///
1<param name="transaction"/>
A valid SqlTransaction
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParamters used to execute the command
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] 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, commandParameters, out mustCloseConnection );
// 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;
}
}
///
1<summary>
2/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
3/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
4/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
5/// </summary>
///
1<remarks>
2/// This method provides no access to output parameters or the stored procedure's return value parameter.
3///
4/// e.g.:
5/// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
6/// </remarks>
///
1<param name="transaction"/>
A valid SqlTransaction
///
1<param name="spName"/>
The name of the stored procedure
///
1<param name="parameterValues"/>
An array of objects to be assigned as the input values of the stored procedure
///
1<returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
{
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" );
if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
// If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takes an array of SqlParameters
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion ExecuteDataset
#region ExecuteReader
///
1<summary>
2/// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
3/// we can set the appropriate CommandBehavior when calling ExecuteReader()
4/// </summary>
private enum SqlConnectionOwnership
{
///
1<summary>Connection is owned and managed by SqlHelper</summary>
Internal,
///
1<summary>Connection is owned and managed by the caller</summary>
External
}
///
1<summary>
2/// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
3/// </summary>
///
1<remarks>
2/// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
3///
4/// If the caller provided the connection, we want to leave it to them to manage.
5/// </remarks>
///
1<param name="connection"/>
A valid SqlConnection, on which to execute this command
///
1<param name="transaction"/>
A valid SqlTransaction, or 'null'
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
///
1<param name="commandText"/>
The stored procedure name or T-SQL command
///
1<param name="commandParameters"/>
An array of SqlParameters to be associated with the command or 'null' if no parameters are required
///
1<param name="connectionOwnership"/>
Indicates whether the connection parameter was provided by the caller, or created by SqlHelper
///
1<returns>SqlDataReader containing the results of the command</returns>
private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
{
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, commandParameters, out mustCloseConnection );
// 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;
}
}
///
1<summary>
2/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
3/// the connection string.
4/// </summary>
///
1<remarks>
2/// e.g.:
3/// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
4/// </remarks>
///
1<param name="connectionString"/>
A valid connection string for a SqlConnection
///
1<param name="commandType"/>
The CommandType (stored procedure, text, etc.)
/// <param name="c