loyung

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  silverlight(简称SL)进行数据库操作,有多种方法,这里介绍最传统的通过WebService(简称WS)实现方式。本文的主要目的是在SL不支持DataSet和DataTable的基础上,提供通用的返回数据的WS方法。

一:创建项目
    首先,创建SL应用程序,如QuestionsDbSL,创建的时候选择生成网站QuestionsDbSL.Web。另外,往往大家不想将SQL语句写在主应用程序中,所以,这里还需要创建一个业务层QuestionsDbSLServices。同时,实体层,我们创建为QuestionsDbSLModel。
    QuestionsDbSL:SL主应用程序;
    QuestionsDbSL.Web:承载SL主应用程序的网站,同时也提供WS;
    QuestionsDbSLServices:SL类库项目,提供逻辑层;
    QuestionsDbSLModel:SL类库项目,提供实体层,对应数据库表。
 
二:必要的辅助类和文件
    第一个辅助类,就是SqlHelper,对数据库的直接操作,由它提供直接对数据库的操作。见附件一:SqlHelper.cs。该文件创建在QuestionsDbSL.Web.ClientBin中。
    第二个是配置文件Web.config,这里需要用到的是定义数据连接字符串:
View Code
1  <ppSettings>
2   <add key="ConnString" value="server =192.168.0.96; user id = sa; password = sa; database = xxxProp"/>
3  </appSettings>

三:WS函数

    首先是获取记录集的函数:
    public List<BaseVars> GetListBaseVars(string sql, params SqlParameter[] commandParams)
    很遗憾的一点是,SL不支持DataSet或者DataTable,所以你无法直接返回一个记录集。但你可以通过返回一个List的方法来迂回解决。
    如数据库表Student,则你可以返回一个List<Student>。问题的关键是,这样一来,你不得不为每一类查询提供一个WS函数。也许你会尝试用List<T>来解决这个问题,同样遗憾的是,SL调用WS函数的时候,只能序列化一般类型的类,所以我们必须换一个方式解决该问题。
    要知道,数据表也就是各种基础类型的字段所组成的,所以,我们来模拟一张表就是:
View Code
 1   /// <summary>
 2     /// 模拟数据库表
 3     /// PS:一张表的字段不外乎几个基本数据类型,查询出来的值,在这里进行赋值
 4     /// 本类的一个实例,相当于是一条记录,本类的一个实例数组,就相当于是datatable
 5     /// 在UI端,你可将本类的实例数组转换为数据源
 6     /// </summary>
 7     public class BaseVars
 8     {
 9         public BaseVars()
10         {
11             ListString = new List<string>();
12             ListInt = new List<int>();
13             ListBool = new List<bool>();
14             ListByte = new List<byte>();
15             ListFloat = new List<float>();
16             ListDouble = new List<double>();
17         }
18         public List<string> ListString { get; set; }
19         public List<int> ListInt { get; set; }
20         public List<bool> ListBool { get; set; }
21         public List<byte> ListByte { get; set; }
22         public List<float> ListFloat { get; set; }
23         public List<double> ListDouble { get; set; }
24     }
25     则,WS函数就是如下:
26         /// <summary>
27         /// 通用查询方法
28         /// 1:查询返回的记录,将会生成实例BaseVars;
29         /// 2:本方法返回BaseVars的列表;
30         /// 3:在调用方,要重新对数据进行组织,以便进行展示;
31         /// </summary>
32         /// <param name="sql"></param>
33         /// <param name="commandParams"></param>
34         /// <returns></returns>
35         [WebMethod]
36         public List<BaseVars> GetListBaseVars(string sql, params SqlParameter[] commandParams)
37         {
38             List<BaseVars> lr = new List<BaseVars>();
39             using (DataSet ds = SqlHelper.ExecuteDataSet(sql, commandParams))
40             {
41                 if (ds == null || ds.Tables[0].Rows.Count < 0)
42                 {
43                     return null;
44                 }
45                 lr = ListBaseDataSet.DataSetToListBaseVars(ds, 0);
46             }
47             return lr;
48         }

 注意到上段代码中,ListBaseDataSet.DataSetToListBaseVars(ds, 0)就是将一个DataSet转换为BaseVars的一个实例列表。ListBaseDataSet.cs见附件二。

 
四:WS调用方
    WS的调用在SL都是异步调用,WS提供的函数名在调用方都会被自动加上一个后缀Async。所以,如果你觉得有必要,你就需要提供一个委托函数来在WS调用完毕的做点什么,如下:
View Code
1 wss.GetListBaseVarsCompleted += new EventHandler<QuestionsDbSLServices.ServiceReferenceYi.GetListBaseVarsCompletedEventArgs>(wss_GetListBaseVarsCompleted);

  wss是WS的实例,wss_GetListBaseVarsCompleted就是该委托函数。在该委托函数中,我是将得到的数据记录重构成一个具体对象的列表。

View Code
 1     void wss_GetListBaseVarsCompleted(object sender, QuestionsDbSLServices.ServiceReferenceYi.GetListBaseVarsCompletedEventArgs e)
 2         {
 3             ServiceReferenceYi.BaseVars[] lr = e.Result;
 4             foreach (var item in lr)
 5             {
 6                 QuestionsDbSLModel.Res_Source ds = new QuestionsDbSLModel.Res_Source();
 7                 ds.SourceId = item.ListInt[0];
 8                 ds.SourceName = item.ListString[0];
 9                 ds.DispOrder = item.ListInt[1];
10                 ldResource.Add(ds);
11             }
12         }
五:一个BUG
     在业务层QuestionsDbSLServices引用WS后,在QuestionsDbSL使用QuestionsDbSLServices后会报错,查询结果是配置文件ServiceReferences.ClientConfig未被包含在XAP中。如果你直接在WEB中调用WS,则在打包项目的时候,ServiceReferences.ClientConfig被自动打包进去。
    解决的办法是,你在WEB中,需要手动创建一个ServiceReferences.ClientConfig,然后将QuestionsDbSLServices的该文件的内容COPY进去。
SqlHelper.cs实例如下:
View Code
   1 using System;
   2 using System.Collections.Generic;
   3 using System.Linq;
   4 using System.Web;
   5 using System.Data.SqlClient;
   6 using System.Configuration;
   7 using System.Data;
   8 using System.Xml;
   9 using System.Diagnostics;
  10 
  11 namespace QuestionsDbSL.Web.ClientBin
  12 {
  13     [DebuggerStepThrough]
  14     public sealed class SqlHelper
  15     {
  16         #region private utility methods & constructors
  17 
  18         //Since this class provides only static methods, make the default constructor private to prevent 
  19         //instances from being created with "new SqlHelper()".
  20         private SqlHelper() { }
  21 
  22         /// <summary>
  23         /// This method is used to attach array of SqlParameters to a SqlCommand.
  24         /// This method will assign a value of DbNull to any parameter with a direction of
  25         /// InputOutput and a value of null.
  26         /// This behavior will prevent default values from being used, but
  27         /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
  28         /// where the user provided no input value.
  29         /// </summary>
  30         /// <param name="command">The command to which the parameters will be added</param>
  31         /// <param name="commandParameters">an array of SqlParameters tho be added to command</param>
  32         private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
  33         {
  34             foreach (SqlParameter p in commandParameters)
  35             {
  36                 //check for derived output value with no value assigned
  37                 if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
  38                 {
  39                     p.Value = DBNull.Value;
  40                 }
  41                 command.Parameters.Add(p);
  42             }
  43         }
  44 
  45         /// <summary>
  46         /// This method assigns an array of values to an array of SqlParameters.
  47         /// </summary>
  48         /// <param name="commandParameters">array of SqlParameters to be assigned values</param>
  49         /// <param name="parameterValues">array of Components holding the values to be assigned</param>
  50         private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
  51         {
  52             if ((commandParameters == null) || (parameterValues == null))
  53             {
  54                 //do nothing if we get no data
  55                 return;
  56             }
  57 
  58             // we must have the same number of values as we pave parameters to put them in
  59             if (commandParameters.Length != parameterValues.Length)
  60             {
  61                 throw new ArgumentException("Parameter count does not match Parameter Value count.");
  62             }
  63 
  64             //iterate through the SqlParameters, assigning the values from the corresponding position in the 
  65             //value array
  66             for (int i = 0, j = commandParameters.Length; i < j; i++)
  67             {
  68                 commandParameters[i].Value = parameterValues[i];
  69             }
  70         }
  71 
  72         /// <summary>
  73         /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters 
  74         /// to the provided command.
  75         /// </summary>
  76         /// <param name="command">the SqlCommand to be prepared</param>
  77         /// <param name="connection">a valid SqlConnection, on which to execute this command</param>
  78         /// <param name="transaction">a valid SqlTransaction, or 'null'</param>
  79         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
  80         /// <param name="commandText">the stored procedure name or T-SQL command</param>
  81         /// <param name="commandParameters">an array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  82         private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
  83         {
  84             //if the provided connection is not open, we will open it
  85             if (connection.State != ConnectionState.Open)
  86                 connection.Open();
  87 
  88             //associate the connection with the command
  89             command.Connection = connection;
  90             command.CommandTimeout = 180;
  91 
  92             //set the command text (stored procedure name or SQL statement)
  93             command.CommandText = commandText;
  94 
  95             //if we were provided a transaction, assign it.
  96             if (transaction != null)
  97                 command.Transaction = transaction;
  98 
  99             //set the command type
 100             command.CommandType = commandType;
 101 
 102             //attach the command parameters if they are provided
 103             if (commandParameters != null)
 104                 AttachParameters(command, commandParameters);
 105 
 106             return;
 107         }
 108 
 109 
 110         #endregion private utility methods & constructors
 111 
 112         #region DataHelpers
 113 
 114         public static string CheckNull(object obj)
 115         {
 116             return (string)obj;
 117         }
 118 
 119         public static string CheckNull(DBNull obj)
 120         {
 121             return null;
 122         }
 123 
 124         #endregion
 125 
 126         #region AddParameters
 127 
 128         public static object CheckForNullString(string text)
 129         {
 130             if (text == null || text.Trim().Length == 0)
 131             {
 132                 return DBNull.Value;
 133             }
 134             else
 135             {
 136                 return text;
 137             }
 138         }
 139 
 140         public static SqlParameter MakeInParam(string ParamName, object Value)
 141         {
 142             return new SqlParameter(ParamName, Value);
 143         }
 144 
 145         /// <summary>
 146         /// Make input param.
 147         /// </summary>
 148         /// <param name="ParamName">Name of param.</param>
 149         /// <param name="DbType">Param type.</param>
 150         /// <param name="Size">Param size.</param>
 151         /// <param name="Value">Param value.</param>
 152         /// <returns>New parameter.</returns>
 153         public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value)
 154         {
 155             return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
 156         }
 157 
 158         /// <summary>
 159         /// Make input param.
 160         /// </summary>
 161         /// <param name="ParamName">Name of param.</param>
 162         /// <param name="DbType">Param type.</param>
 163         /// <param name="Size">Param size.</param>
 164         /// <returns>New parameter.</returns>
 165         public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size)
 166         {
 167             return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
 168         }
 169 
 170         /// <summary>
 171         /// Make stored procedure param.
 172         /// </summary>
 173         /// <param name="ParamName">Name of param.</param>
 174         /// <param name="DbType">Param type.</param>
 175         /// <param name="Size">Param size.</param>
 176         /// <param name="Direction">Parm direction.</param>
 177         /// <param name="Value">Param value.</param>
 178         /// <returns>New parameter.</returns>
 179         public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
 180         {
 181             SqlParameter param;
 182 
 183             if (Size > 0)
 184                 param = new SqlParameter(ParamName, DbType, Size);
 185             else
 186                 param = new SqlParameter(ParamName, DbType);
 187 
 188             param.Direction = Direction;
 189             if (!(Direction == ParameterDirection.Output && Value == null))
 190                 param.Value = Value;
 191 
 192             return param;
 193         }
 194 
 195 
 196         #endregion
 197 
 198         #region ExecuteNonQuery
 199 
 200         /// <summary>
 201         /// 执行一个简单的Sqlcommand 没有返回结果
 202         /// </summary>
 203         ///  例如:  
 204         ///  int result = ExecuteNonQuery("delete from test where 1>2 ");  返回 result =0
 205         /// <param name="commandText">只能是sql语句</param>
 206         /// <returns>受影响的行数</returns>
 207         public static int ExecuteNonQuery(string commandText)
 208         {
 209             return ExecuteNonQuery(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, (SqlParameter[])null);
 210         }
 211 
 212         /// <summary>
 213         /// 执行一个简单的Sqlcommand 没有返回结果
 214         /// </summary>
 215         /// 例如:    
 216         ///  int result = ExecuteNonQuery("delete from test where  tt =@tt", new SqlParameter("@tt", 24));
 217         /// <param name="commandText">只能是sql语句</param>
 218         /// <param name="commandParameters">参数</param>
 219         /// <returns>受影响的行数</returns>
 220         public static int ExecuteNonQuery(string commandText, params SqlParameter[] commandParameters)
 221         {
 222             int i = 0;
 223             using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
 224             {
 225                 cn.Open();
 226                 return ExecuteNonQuery(cn, CommandType.Text, commandText, commandParameters);
 227             }
 228         }
 229 
 230         /// <summary>
 231         /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in 
 232         /// the connection string. 
 233         /// </summary>
 234         /// <remarks>
 235         /// e.g.:  
 236         ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
 237         /// </remarks>
 238         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 239         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 240         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 241         /// <returns>an int representing the number of rows affected by the command</returns>
 242         public static int ExecuteNonQuery(string connectionString, string commandText)
 243         {
 244             //pass through the call providing null for the set of SqlParameters
 245             return ExecuteNonQuery(connectionString, CommandType.Text, commandText, (SqlParameter[])null);
 246         }
 247 
 248         /// <summary>
 249         /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in 
 250         /// the connection string. 
 251         /// </summary>
 252         /// <remarks>
 253         /// e.g.:  
 254         ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
 255         /// </remarks>
 256         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 257         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 258         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 259         /// <returns>an int representing the number of rows affected by the command</returns>
 260         public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
 261         {
 262             //pass through the call providing null for the set of SqlParameters
 263             return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
 264         }
 265 
 266         /// <summary>
 267         /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
 268         /// using the provided parameters.
 269         /// </summary>
 270         /// <remarks>
 271         /// e.g.:  
 272         ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
 273         /// </remarks>
 274         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 275         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 276         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 277         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 278         /// <returns>an int representing the number of rows affected by the command</returns>
 279         public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 280         {
 281             //create & open a SqlConnection, and dispose of it after we are done.
 282             using (SqlConnection cn = new SqlConnection(connectionString))
 283             {
 284                 cn.Open();
 285 
 286                 //call the overload that takes a connection in place of the connection string
 287                 return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
 288             }
 289         }
 290 
 291         /// <summary>
 292         /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection. 
 293         /// </summary>
 294         /// <remarks>
 295         /// e.g.:  
 296         ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
 297         /// </remarks>
 298         /// <param name="connection">a valid SqlConnection</param>
 299         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 300         /// <returns>an int representing the number of rows affected by the command</returns>
 301         public static int ExecuteNonQuery(SqlConnection connection, string commandText)
 302         {
 303             //pass through the call providing null for the set of SqlParameters
 304             return ExecuteNonQuery(connection, CommandType.Text, commandText, (SqlParameter[])null);
 305         }
 306 
 307         /// <summary>
 308         /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection. 
 309         /// </summary>
 310         /// <remarks>
 311         /// e.g.:  
 312         ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
 313         /// </remarks>
 314         /// <param name="connection">a valid SqlConnection</param>
 315         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 316         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 317         /// <returns>an int representing the number of rows affected by the command</returns>
 318         public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
 319         {
 320             //pass through the call providing null for the set of SqlParameters
 321             return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
 322         }
 323 
 324         /// <summary>
 325         /// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection 
 326         /// using the provided parameters.
 327         /// </summary>
 328         /// <remarks>
 329         /// e.g.:  
 330         ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
 331         /// </remarks>
 332         /// <param name="connection">a valid SqlConnection</param>
 333         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 334         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 335         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 336         /// <returns>an int representing the number of rows affected by the command</returns>
 337         public static int ExecuteNonQuery(SqlConnection connection, string commandText, params SqlParameter[] commandParameters)
 338         {
 339             return ExecuteNonQuery(connection, CommandType.Text, commandText, commandParameters);
 340         }
 341 
 342         /// <summary>
 343         /// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection 
 344         /// using the provided parameters.
 345         /// </summary>
 346         /// <remarks>
 347         /// e.g.:  
 348         ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
 349         /// </remarks>
 350         /// <param name="connection">a valid SqlConnection</param>
 351         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 352         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 353         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 354         /// <returns>an int representing the number of rows affected by the command</returns>
 355         public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 356         {
 357             //create a command and prepare it for execution
 358             SqlCommand cmd = new SqlCommand();
 359             PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
 360 
 361             //finally, execute the command.
 362             int retval = cmd.ExecuteNonQuery();
 363 
 364             // detach the SqlParameters from the command object, so they can be used again.
 365             cmd.Parameters.Clear();
 366             if (connection.State == ConnectionState.Open)
 367                 connection.Close();
 368             return retval;
 369         }
 370 
 371         /// <summary>
 372         /// 执行一个简单的Sqlcommand 没有返回结果
 373         /// </summary>
 374         ///  例如:  
 375         ///  int result = ExecuteNonQuery(myTran,"delete from test where 1>2 ");  返回 result =0
 376         /// <param name="transaction">事务名称</param>
 377         /// <param name="commandText">只能是sql语句</param>
 378         /// <returns>受影响的行数</returns>
 379         public static int ExecuteNonQuery(SqlTransaction transaction, string commandText)
 380         {
 381             return ExecuteNonQuery(transaction, CommandType.Text, commandText, (SqlParameter[])null);
 382         }
 383 
 384         /// <summary>
 385         /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction. 
 386         /// </summary>
 387         /// <remarks>
 388         /// e.g.:  
 389         ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
 390         /// </remarks>
 391         /// <param name="transaction">a valid SqlTransaction</param>
 392         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 393         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 394         /// <returns>an int representing the number of rows affected by the command</returns>
 395         public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
 396         {
 397             //pass through the call providing null for the set of SqlParameters
 398             return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
 399         }
 400 
 401         /// <summary>
 402         /// 带参数和参数的查询
 403         /// </summary>
 404         /// <param name="transaction"></param>
 405         /// <param name="commandText"></param>
 406         /// <param name="commandParameters"></param>
 407         /// <returns></returns>
 408         public static int ExecuteNonQuery(SqlTransaction transaction, string commandText, params SqlParameter[] commandParameters)
 409         {
 410             //pass through the call providing null for the set of SqlParameters
 411             return ExecuteNonQuery(transaction, CommandType.Text, commandText, commandParameters);
 412         }
 413 
 414         /// <summary>
 415         /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
 416         /// using the provided parameters.
 417         /// </summary>
 418         /// <remarks>
 419         /// e.g.:  
 420         ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
 421         /// </remarks>
 422         /// <param name="transaction">a valid SqlTransaction</param>
 423         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 424         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 425         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 426         /// <returns>an int representing the number of rows affected by the command</returns>
 427         public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 428         {
 429             if (transaction == null)
 430             {
 431                 //create & open a SqlConnection, and dispose of it after we are done.
 432                 using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
 433                 {
 434                     cn.Open();
 435 
 436                     //call the overload that takes a connection in place of the connection string
 437                     return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
 438                 }
 439             }
 440             else
 441             {
 442                 //create a command and prepare it for execution
 443                 SqlCommand cmd = new SqlCommand();
 444                 PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
 445 
 446                 //finally, execute the command.
 447                 int retval = cmd.ExecuteNonQuery();
 448 
 449                 // detach the SqlParameters from the command object, so they can be used again.
 450                 cmd.Parameters.Clear();
 451                 return retval;
 452             }
 453         }
 454 
 455         #endregion ExecuteNonQuery
 456 
 457         #region 执行SqlDataAdapter
 458         public static SqlDataAdapter ExecuteSqlDataAdapter(string commandText)
 459         {
 460             using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
 461             {
 462                 cn.Open();
 463                 return ExecuteSqlDataAdapter(cn, commandText);
 464             }
 465         }
 466 
 467         public static SqlDataAdapter ExecuteSqlDataAdapter(SqlConnection connection, string commandText)
 468         {
 469             SqlDataAdapter myda = new SqlDataAdapter(commandText, connection);
 470             myda.SelectCommand.CommandTimeout = 180;
 471             connection.Close();
 472             return myda;
 473         }
 474 
 475         #endregion
 476 
 477         #region ExecuteDataSet
 478 
 479         /// <summary>
 480         /// 返回datataset 只需要传入查询语句
 481         /// </summary>
 482         /// <param name="commandText"></param>
 483         /// <returns></returns>
 484         public static DataSet ExecuteDataSet(string commandText)
 485         {
 486             //pass through the call providing null for the set of SqlParameters
 487             return ExecuteDataSet(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, (SqlParameter[])null);
 488         }
 489 
 490         /// <summary>
 491         /// 带参数查询
 492         /// </summary>
 493         /// <param name="commandText"></param>
 494         /// <param name="commandParameters"></param>
 495         /// <returns></returns>
 496         public static DataSet ExecuteDataSet(string commandText, params SqlParameter[] commandParameters)
 497         {
 498             using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
 499             {
 500                 cn.Open();
 501                 return ExecuteDataSet(cn, CommandType.Text, commandText, commandParameters);
 502             }
 503         }
 504 
 505         /// <summary>
 506         /// 执行存储过程 返回相应的dataset
 507         /// </summary>
 508         /// <param name="commandText">存储过程名字</param>
 509         /// <param name="commandType"></param>
 510         /// <param name="commandParameters"></param>
 511         /// <returns></returns>
 512         public static DataSet ExecuteDataSet(string commandText, CommandType commandType, params SqlParameter[] commandParameters)
 513         {
 514             using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
 515             {
 516                 cn.Open();
 517                 return ExecuteDataSet(cn, commandType, commandText, commandParameters);
 518             }
 519         }
 520 
 521         /// <summary>
 522         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
 523         /// the connection string. 
 524         /// </summary>
 525         /// <remarks>
 526         /// e.g.:  
 527         ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
 528         /// </remarks>
 529         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 530         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 531         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 532         /// <returns>a dataset containing the resultset generated by the command</returns>
 533         public static DataSet ExecuteDataSet(string connectionString, string commandText)
 534         {
 535             //pass through the call providing null for the set of SqlParameters
 536             return ExecuteDataSet(connectionString, CommandType.Text, commandText, (SqlParameter[])null);
 537         }
 538 
 539         /// <summary>
 540         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
 541         /// the connection string. 
 542         /// </summary>
 543         /// <remarks>
 544         /// e.g.:  
 545         ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
 546         /// </remarks>
 547         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 548         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 549         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 550         /// <returns>a dataset containing the resultset generated by the command</returns>
 551         public static DataSet ExecuteDataSet(string connectionString, CommandType commandType, string commandText)
 552         {
 553             //pass through the call providing null for the set of SqlParameters
 554             return ExecuteDataSet(connectionString, commandType, commandText, (SqlParameter[])null);
 555         }
 556 
 557         /// <summary>
 558         /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
 559         /// using the provided parameters.
 560         /// </summary>
 561         /// <remarks>
 562         /// e.g.:  
 563         ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
 564         /// </remarks>
 565         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 566         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 567         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 568         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 569         /// <returns>a dataset containing the resultset generated by the command</returns>
 570         public static DataSet ExecuteDataSet(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 571         {
 572             //create & open a SqlConnection, and dispose of it after we are done.
 573             try
 574             {
 575                 using (SqlConnection cn = new SqlConnection(connectionString))
 576                 {
 577                     cn.Open();
 578 
 579 
 580                     //call the overload that takes a connection in place of the connection string
 581                     return ExecuteDataSet(cn, commandType, commandText, commandParameters);
 582                 }
 583             }
 584             catch (Exception e)
 585             {
 586 
 587                 throw e;
 588             }
 589         }
 590 
 591         /// <summary>
 592         /// 返回datataset 只需要传入查询语句
 593         /// </summary>
 594         /// <param name="commandText"></param>
 595         /// <returns></returns>
 596         public static DataSet ExecuteDataSet(SqlConnection connection, string commandText)
 597         {
 598             //pass through the call providing null for the set of SqlParameters
 599             return ExecuteDataSet(connection, CommandType.Text, commandText);
 600         }
 601 
 602         /// <summary>
 603         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
 604         /// </summary>
 605         /// <remarks>
 606         /// e.g.:  
 607         ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
 608         /// </remarks>
 609         /// <param name="connection">a valid SqlConnection</param>
 610         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 611         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 612         /// <returns>a dataset containing the resultset generated by the command</returns>
 613         public static DataSet ExecuteDataSet(SqlConnection connection, CommandType commandType, string commandText)
 614         {
 615             //pass through the call providing null for the set of SqlParameters
 616             return ExecuteDataSet(connection, commandType, commandText, (SqlParameter[])null);
 617         }
 618 
 619         /// <summary>
 620         /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
 621         /// using the provided parameters.
 622         /// </summary>
 623         /// <remarks>
 624         /// e.g.:  
 625         ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
 626         /// </remarks>
 627         /// <param name="connection">a valid SqlConnection</param>
 628         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 629         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 630         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 631         /// <returns>a dataset containing the resultset generated by the command</returns>
 632         public static DataSet ExecuteDataSet(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 633         {
 634             //create a command and prepare it for execution
 635             SqlCommand cmd = new SqlCommand();
 636             PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
 637 
 638             //create the DataAdapter & DataSet
 639             SqlDataAdapter da = new SqlDataAdapter(cmd);
 640             DataSet ds = new DataSet();
 641 
 642             //fill the DataSet using default values for DataTable names, etc.
 643             da.Fill(ds);
 644 
 645             // detach the SqlParameters from the command object, so they can be used again.   
 646             cmd.Parameters.Clear();
 647 
 648             if (connection.State == ConnectionState.Open)
 649                 connection.Close();
 650             //return the dataset
 651             return ds;
 652         }
 653 
 654         /// <summary>
 655         /// s事务中执行返回dataset
 656         /// </summary>
 657         /// <param name="transaction"></param>
 658         /// <param name="commandText"></param>
 659         /// <returns></returns>
 660         public static DataSet ExecuteDataSet(SqlTransaction transaction, string commandText)
 661         {
 662             //pass through the call providing null for the set of SqlParameters
 663             return ExecuteDataSet(transaction, CommandType.Text, commandText, (SqlParameter[])null);
 664         }
 665 
 666         /// <summary>
 667         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
 668         /// </summary>
 669         /// <remarks>
 670         /// e.g.:  
 671         ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
 672         /// </remarks>
 673         /// <param name="transaction">a valid SqlTransaction</param>
 674         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 675         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 676         /// <returns>a dataset containing the resultset generated by the command</returns>
 677         public static DataSet ExecuteDataSet(SqlTransaction transaction, CommandType commandType, string commandText)
 678         {
 679             //pass through the call providing null for the set of SqlParameters
 680             return ExecuteDataSet(transaction, commandType, commandText, (SqlParameter[])null);
 681         }
 682 
 683         /// <summary>
 684         /// 事务中返回dataset 可带参数
 685         /// </summary>
 686         /// <param name="transaction"></param>
 687         /// <param name="commandText"></param>
 688         /// <param name="commandParameters"></param>
 689         /// <returns></returns>
 690         public static DataSet ExecuteDataSet(SqlTransaction transaction, string commandText, params SqlParameter[] commandParameters)
 691         {
 692             //pass through the call providing null for the set of SqlParameters
 693             return ExecuteDataSet(transaction, CommandType.Text, commandText, (SqlParameter[])null);
 694         }
 695 
 696         /// <summary>
 697         /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
 698         /// using the provided parameters.
 699         /// </summary>
 700         /// <remarks>
 701         /// e.g.:  
 702         ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
 703         /// </remarks>
 704         /// <param name="transaction">a valid SqlTransaction</param>
 705         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 706         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 707         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 708         /// <returns>a dataset containing the resultset generated by the command</returns>
 709         public static DataSet ExecuteDataSet(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 710         {
 711             if (transaction == null)
 712             {
 713                 //create & open a SqlConnection, and dispose of it after we are done.
 714                 using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
 715                 {
 716                     cn.Open();
 717 
 718                     //call the overload that takes a connection in place of the connection string
 719                     return ExecuteDataSet(cn, commandType, commandText, commandParameters);
 720                 }
 721             }
 722             else
 723             {
 724                 //create a command and prepare it for execution
 725                 SqlCommand cmd = new SqlCommand();
 726                 PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
 727 
 728                 //create the DataAdapter & DataSet
 729                 SqlDataAdapter da = new SqlDataAdapter(cmd);
 730                 DataSet ds = new DataSet();
 731 
 732                 //fill the DataSet using default values for DataTable names, etc.
 733                 da.Fill(ds);
 734 
 735                 // detach the SqlParameters from the command object, so they can be used again.
 736                 cmd.Parameters.Clear();
 737 
 738                 //return the dataset
 739                 return ds;
 740             }
 741         }
 742 
 743         #endregion ExecuteDataSet
 744 
 745         #region ExecuteDataTable
 746 
 747         /// <summary>
 748         /// 连接数据库
 749         /// </summary>
 750         /// <param name="commandText"></param>
 751         /// <returns></returns>
 752         public static DataTable ExecuteDataTable(string commandText)
 753         {
 754             //pass through the call providing null for the set of SqlParameters
 755             return ExecuteDataTable(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, (SqlParameter[])null);
 756         }
 757 
 758         /// <summary>
 759         /// 连接数据库
 760         /// </summary>
 761         /// <param name="commandText"></param>
 762         /// <returns></returns>
 763         public static DataTable ExecuteDataTable(string commandText, params SqlParameter[] commandParameters)
 764         {
 765             //pass through the call providing null for the set of SqlParameters
 766             return ExecuteDataTable(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, commandParameters);
 767         }
 768 
 769         /// <summary>
 770         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
 771         /// the connection string. 
 772         /// </summary>
 773         /// <remarks>
 774         /// e.g.:  
 775         ///  DataTable dt = ExecuteDataTable(connString, CommandType.StoredProcedure, "GetOrders");
 776         /// </remarks>
 777         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 778         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 779         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 780         /// <returns>a DataTable containing the resultset generated by the command</returns>
 781         public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText)
 782         {
 783             //pass through the call providing null for the set of SqlParameters
 784             return ExecuteDataTable(connectionString, commandType, commandText, (SqlParameter[])null);
 785         }
 786 
 787         /// <summary>
 788         /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
 789         /// using the provided parameters.
 790         /// </summary>
 791         /// <remarks>
 792         /// e.g.:  
 793         ///  DataTable dt = ExecuteDataTable(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
 794         /// </remarks>
 795         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
 796         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 797         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 798         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 799         /// <returns>a DataTable containing the resultset generated by the command</returns>
 800         public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 801         {
 802             //create & open a SqlConnection, and dispose of it after we are done.
 803             using (SqlConnection cn = new SqlConnection(connectionString))
 804             {
 805                 cn.Open();
 806 
 807                 //call the overload that takes a connection in place of the connection string
 808                 return ExecuteDataTable(cn, commandType, commandText, commandParameters);
 809             }
 810         }
 811 
 812         /// <summary>
 813         /// 连接数据库
 814         /// </summary>
 815         /// <param name="commandText"></param>
 816         /// <returns></returns>
 817         public static DataTable ExecuteDataTable(SqlConnection connection, string commandText)
 818         {
 819             //pass through the call providing null for the set of SqlParameters
 820             return ExecuteDataTable(connection, CommandType.Text, commandText);
 821         }
 822 
 823         /// <summary>
 824         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
 825         /// </summary>
 826         /// <remarks>
 827         /// e.g.:  
 828         ///  DataTable dt = ExecuteDataTable(conn, CommandType.StoredProcedure, "GetOrders");
 829         /// </remarks>
 830         /// <param name="connection">a valid SqlConnection</param>
 831         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 832         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 833         /// <returns>a DataTable containing the resultset generated by the command</returns>
 834         public static DataTable ExecuteDataTable(SqlConnection connection, CommandType commandType, string commandText)
 835         {
 836             //pass through the call providing null for the set of SqlParameters
 837             return ExecuteDataTable(connection, commandType, commandText, (SqlParameter[])null);
 838         }
 839 
 840         /// <summary>
 841         /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
 842         /// using the provided parameters.
 843         /// </summary>
 844         /// <remarks>
 845         /// e.g.:  
 846         ///  DataTable dt = ExecuteDataTable(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
 847         /// </remarks>
 848         /// <param name="connection">a valid SqlConnection</param>
 849         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 850         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 851         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 852         /// <returns>a DataTable containing the resultset generated by the command</returns>
 853         public static DataTable ExecuteDataTable(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 854         {
 855             //create a command and prepare it for execution
 856             SqlCommand cmd = new SqlCommand();
 857             PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
 858 
 859             //create the DataAdapter & DataTable
 860             SqlDataAdapter da = new SqlDataAdapter(cmd);
 861             DataTable dt = new DataTable();
 862 
 863             //fill the DataTable using default values for DataTable names, etc.
 864             da.Fill(dt);
 865 
 866             // detach the SqlParameters from the command object, so they can be used again.   
 867             cmd.Parameters.Clear();
 868 
 869             if (connection.State == ConnectionState.Open)
 870                 connection.Close();
 871             //return the DataTable
 872             return dt;
 873         }
 874 
 875         /// <summary>
 876         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
 877         /// </summary>
 878         /// <remarks>
 879         /// e.g.:  
 880         ///  DataTable dt = ExecuteDataTable(trans, CommandType.StoredProcedure, "GetOrders");
 881         /// </remarks>
 882         /// <param name="transaction">a valid SqlTransaction</param>
 883         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 884         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 885         /// <returns>a DataTable containing the resultset generated by the command</returns>
 886         public static DataTable ExecuteDataTable(SqlTransaction transaction, string commandText)
 887         {
 888             //pass through the call providing null for the set of SqlParameters
 889             return ExecuteDataTable(transaction, CommandType.Text, commandText, (SqlParameter[])null);
 890         }
 891 
 892         /// <summary>
 893         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
 894         /// </summary>
 895         /// <remarks>
 896         /// e.g.:  
 897         ///  DataTable dt = ExecuteDataTable(trans, CommandType.StoredProcedure, "GetOrders");
 898         /// </remarks>
 899         /// <param name="transaction">a valid SqlTransaction</param>
 900         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 901         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 902         /// <returns>a DataTable containing the resultset generated by the command</returns>
 903         public static DataTable ExecuteDataTable(SqlTransaction transaction, CommandType commandType, string commandText)
 904         {
 905             //pass through the call providing null for the set of SqlParameters
 906             return ExecuteDataTable(transaction, commandType, commandText, (SqlParameter[])null);
 907         }
 908 
 909         /// <summary>
 910         /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
 911         /// using the provided parameters.
 912         /// </summary>
 913         /// <remarks>
 914         /// e.g.:  
 915         ///  DataTable dt = ExecuteDataTable(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
 916         /// </remarks>
 917         /// <param name="transaction">a valid SqlTransaction</param>
 918         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
 919         /// <param name="commandText">the stored procedure name or T-SQL command</param>
 920         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
 921         /// <returns>a DataTable containing the resultset generated by the command</returns>
 922         public static DataTable ExecuteDataTable(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
 923         {
 924             if (transaction == null)
 925             {
 926                 //create & open a SqlConnection, and dispose of it after we are done.
 927                 using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
 928                 {
 929                     cn.Open();
 930 
 931                     //call the overload that takes a connection in place of the connection string
 932                     return ExecuteDataTable(cn, commandType, commandText, commandParameters);
 933                 }
 934             }
 935             else
 936             {
 937                 //create a command and prepare it for execution
 938                 SqlCommand cmd = new SqlCommand();
 939                 PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
 940 
 941                 //create the DataAdapter & DataTable
 942                 SqlDataAdapter da = new SqlDataAdapter(cmd);
 943                 DataTable dt = new DataTable();
 944 
 945                 //fill the DataTable using default values for DataTable names, etc.
 946                 da.Fill(dt);
 947 
 948                 // detach the SqlParameters from the command object, so they can be used again.
 949                 cmd.Parameters.Clear();
 950 
 951                 //return the DataTable
 952                 return dt;
 953             }
 954         }
 955 
 956         #endregion ExecuteDataTable
 957 
 958         #region ExecuteReader
 959 
 960         /// <summary>
 961         /// this enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
 962         /// we can set the appropriate CommandBehavior when calling ExecuteReader()
 963         /// </summary>
 964         private enum SqlConnectionOwnership
 965         {
 966             /// <summary>Connection is owned and managed by SqlHelper</summary>
 967             Internal,
 968             /// <summary>Connection is owned and managed by the caller</summary>
 969             External
 970         }
 971 
 972         /// <summary>
 973         /// 返回SqlDataReader 只是传入一条sql语句
 974         /// </summary>
 975         /// <param name="commandText">sql语句</param>
 976         /// <returns></returns>
 977         public static SqlDataReader ExecuteReader(string commandText)
 978         {
 979             return ExecuteReader(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, (SqlParameter[])null);
 980         }
 981 
 982         /// <summary>
 983         /// 返回SqlDataReader 只是传入一条sql语句和相应的参数
 984         /// </summary>
 985         /// <param name="commandText"></param>
 986         /// <param name="commandParameters"></param>
 987         /// <returns></returns>
 988         public static SqlDataReader ExecuteReader(string commandText, params SqlParameter[] commandParameters)
 989         {
 990             return ExecuteReader(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, commandParameters);
 991         }
 992 
 993         /// <summary>
 994         /// 返回SqlDataReader 只是传入一条sql语句和相应的参数
 995         /// </summary>
 996         /// <param name="commandText"></param>
 997         /// <param name="commandParameters"></param>
 998         /// <returns></returns>
 999         public static SqlDataReader ExecuteReader(string commandText, CommandType commandType, params SqlParameter[] commandParameters)
1000         {
1001             return ExecuteReader(ConfigurationManager.AppSettings["ConnString"], commandType, commandText, commandParameters);
1002         }
1003 
1004         /// <summary>
1005         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
1006         /// the connection string. 
1007         /// </summary>
1008         /// <remarks>
1009         /// e.g.:  
1010         ///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
1011         /// </remarks>
1012         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
1013         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1014         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1015         /// <returns>a SqlDataReader containing the resultset generated by the command</returns>
1016         public static SqlDataReader ExecuteReader(string connectionString, string commandText)
1017         {
1018             //pass through the call providing null for the set of SqlParameters
1019             return ExecuteReader(connectionString, CommandType.Text, commandText, (SqlParameter[])null);
1020         }
1021 
1022         /// <summary>
1023         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
1024         /// the connection string. 
1025         /// </summary>
1026         /// <remarks>
1027         /// e.g.:  
1028         ///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
1029         /// </remarks>
1030         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
1031         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1032         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1033         /// <returns>a SqlDataReader containing the resultset generated by the command</returns>
1034         public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
1035         {
1036             //pass through the call providing null for the set of SqlParameters
1037             return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
1038         }
1039 
1040         /// <summary>
1041         /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
1042         /// using the provided parameters.
1043         /// </summary>
1044         /// <remarks>
1045         /// e.g.:  
1046         ///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
1047         /// </remarks>
1048         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
1049         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1050         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1051         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1052         /// <returns>a SqlDataReader containing the resultset generated by the command</returns>
1053         public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1054         {
1055             //create & open a SqlConnection
1056             SqlConnection cn = new SqlConnection(connectionString);
1057             cn.Open();
1058 
1059             try
1060             {
1061                 //call the private overload that takes an internally owned connection in place of the connection string
1062                 return ExecuteReader(cn, null, commandType, commandText, commandParameters, SqlConnectionOwnership.Internal);
1063             }
1064             catch
1065             {
1066                 //if we fail to return the SqlDatReader, we need to close the connection ourselves
1067                 cn.Close();
1068                 throw;
1069             }
1070         }
1071 
1072         /// <summary>
1073         /// 返回SqlDataReader 只是传入一条sql语句
1074         /// </summary>
1075         /// <param name="commandText">sql语句</param>
1076         /// <returns></returns>
1077         public static SqlDataReader ExecuteReader(SqlConnection connection, string commandText)
1078         {
1079             return ExecuteReader(connection, CommandType.Text, commandText, (SqlParameter[])null);
1080         }
1081 
1082         /// <summary>
1083         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
1084         /// </summary>
1085         /// <remarks>
1086         /// e.g.:  
1087         ///  SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
1088         /// </remarks>
1089         /// <param name="connection">a valid SqlConnection</param>
1090         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1091         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1092         /// <returns>a SqlDataReader containing the resultset generated by the command</returns>
1093         public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
1094         {
1095             //pass through the call providing null for the set of SqlParameters
1096             return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
1097         }
1098 
1099         /// <summary>
1100         /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
1101         /// using the provided parameters.
1102         /// </summary>
1103         /// <remarks>
1104         /// e.g.:  
1105         ///  SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
1106         /// </remarks>
1107         /// <param name="connection">a valid SqlConnection</param>
1108         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1109         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1110         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1111         /// <returns>a SqlDataReader containing the resultset generated by the command</returns>
1112         public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1113         {
1114             //pass through the call to the private overload using a null transaction value and an externally owned connection
1115             return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
1116         }
1117 
1118         /// <summary>
1119         /// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
1120         /// </summary>
1121         /// <remarks>
1122         /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
1123         /// 
1124         /// If the caller provided the connection, we want to leave it to them to manage.
1125         /// </remarks>
1126         /// <param name="connection">a valid SqlConnection, on which to execute this command</param>
1127         /// <param name="transaction">a valid SqlTransaction, or 'null'</param>
1128         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1129         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1130         /// <param name="commandParameters">an array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
1131         /// <param name="connectionOwnership">indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
1132         /// <returns>SqlDataReader containing the results of the command</returns>
1133         private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
1134         {
1135             //create a command and prepare it for execution
1136             SqlCommand cmd = new SqlCommand();
1137             PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);
1138 
1139             //create a reader
1140             SqlDataReader dr;
1141 
1142             // call ExecuteReader with the appropriate CommandBehavior
1143             if (connectionOwnership == SqlConnectionOwnership.External)
1144                 dr = cmd.ExecuteReader();
1145             else
1146                 dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
1147 
1148             // detach the SqlParameters from the command object, so they can be used again.
1149             cmd.Parameters.Clear();
1150 
1151             return dr;
1152         }
1153 
1154         /// <summary>
1155         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
1156         /// </summary>
1157         /// <remarks>
1158         /// e.g.:  
1159         ///  SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
1160         /// </remarks>
1161         /// <param name="transaction">a valid SqlTransaction</param>
1162         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1163         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1164         /// <returns>a SqlDataReader containing the resultset generated by the command</returns>
1165         public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
1166         {
1167             //pass through the call providing null for the set of SqlParameters
1168             return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
1169         }
1170 
1171         /// <summary>
1172         /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
1173         /// using the provided parameters.
1174         /// </summary>
1175         /// <remarks>
1176         /// e.g.:  
1177         ///   SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
1178         /// </remarks>
1179         /// <param name="transaction">a valid SqlTransaction</param>
1180         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1181         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1182         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1183         /// <returns>a SqlDataReader containing the resultset generated by the command</returns>
1184         public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1185         {
1186             if (transaction == null)
1187             {
1188                 //create & open a SqlConnection
1189                 SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);
1190                 cn.Open();
1191 
1192                 try
1193                 {
1194                     //call the private overload that takes an internally owned connection in place of the connection string
1195                     return ExecuteReader(cn, null, commandType, commandText, commandParameters, SqlConnectionOwnership.Internal);
1196                 }
1197                 catch
1198                 {
1199                     //if we fail to return the SqlDatReader, we need to close the connection ourselves
1200                     cn.Close();
1201                     throw;
1202                 }
1203             }
1204             else
1205                 //pass through to private overload, indicating that the connection is owned by the caller
1206                 return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
1207         }
1208 
1209         #endregion ExecuteReader
1210 
1211         #region ExecuteScalar
1212 
1213         /// <summary>
1214         /// 返回ExecuteScalar 只是传入一条sql语句
1215         /// </summary>
1216         /// <param name="commandText">sql语句</param>
1217         /// <returns></returns>
1218         public static object ExecuteScalar(string commandText)
1219         {
1220             return ExecuteScalar(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, (SqlParameter[])null);
1221         }
1222 
1223         public static object ExecuteScalar(string commandText, params SqlParameter[] commandParameters)
1224         {
1225             return ExecuteScalar(ConfigurationManager.AppSettings["ConnString"], CommandType.Text, commandText, commandParameters);
1226         }
1227 
1228         /// <summary>
1229         /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in 
1230         /// the connection string. 
1231         /// </summary>
1232         /// <remarks>
1233         /// e.g.:  
1234         ///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
1235         /// </remarks>
1236         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
1237         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1238         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1239         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1240         public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
1241         {
1242             //pass through the call providing null for the set of SqlParameters
1243             return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
1244         }
1245 
1246         /// <summary>
1247         /// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string 
1248         /// using the provided parameters.
1249         /// </summary>
1250         /// <remarks>
1251         /// e.g.:  
1252         ///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
1253         /// </remarks>
1254         /// <param name="connectionString">a valid connection string for a SqlConnection</param>
1255         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1256         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1257         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1258         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1259         public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1260         {
1261             //create & open a SqlConnection, and dispose of it after we are done.
1262             using (SqlConnection cn = new SqlConnection(connectionString))
1263             {
1264                 cn.Open();
1265 
1266                 //call the overload that takes a connection in place of the connection string
1267                 return ExecuteScalar(cn, commandType, commandText, commandParameters);
1268             }
1269         }
1270 
1271         /// <summary>
1272         /// 返回ExecuteScalar 只是传入一条sql语句
1273         /// </summary>
1274         /// <param name="commandText">sql语句</param>
1275         /// <returns></returns>
1276         public static object ExecuteScalar(SqlConnection connection, string commandText)
1277         {
1278             return ExecuteScalar(connection, CommandType.Text, commandText, (SqlParameter[])null);
1279         }
1280 
1281         /// <summary>
1282         /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection. 
1283         /// </summary>
1284         /// <remarks>
1285         /// e.g.:  
1286         ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
1287         /// </remarks>
1288         /// <param name="connection">a valid SqlConnection</param>
1289         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1290         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1291         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1292         public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
1293         {
1294             //pass through the call providing null for the set of SqlParameters
1295             return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
1296         }
1297 
1298         /// <summary>
1299         /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection 
1300         /// using the provided parameters.
1301         /// </summary>
1302         /// <remarks>
1303         /// e.g.:  
1304         ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
1305         /// </remarks>
1306         /// <param name="connection">a valid SqlConnection</param>
1307         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1308         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1309         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1310         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1311         public static object ExecuteScalar(SqlConnection connection, string commandText, params SqlParameter[] commandParameters)
1312         {
1313             //pass through the call providing null for the set of SqlParameters
1314             return ExecuteScalar(connection, CommandType.Text, commandText, commandParameters);
1315         }
1316 
1317         /// <summary>
1318         /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection 
1319         /// using the provided parameters.
1320         /// </summary>
1321         /// <remarks>
1322         /// e.g.:  
1323         ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
1324         /// </remarks>
1325         /// <param name="connection">a valid SqlConnection</param>
1326         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1327         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1328         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1329         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1330         public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1331         {
1332             //create a command and prepare it for execution
1333             SqlCommand cmd = new SqlCommand();
1334             PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
1335 
1336             //execute the command & return the results
1337             object retval = cmd.ExecuteScalar();
1338 
1339             // detach the SqlParameters from the command object, so they can be used again.
1340             cmd.Parameters.Clear();
1341             if (connection.State == ConnectionState.Open)
1342                 connection.Close();
1343             return retval;
1344 
1345         }
1346 
1347         /// <summary>
1348         /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction. 
1349         /// </summary>
1350         /// <remarks>
1351         /// e.g.:  
1352         ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
1353         /// </remarks>
1354         /// <param name="transaction">a valid SqlTransaction</param>
1355         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1356         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1357         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1358         public static object ExecuteScalar(SqlTransaction transaction, string commandText)
1359         {
1360             //pass through the call providing null for the set of SqlParameters
1361             return ExecuteScalar(transaction, CommandType.Text, commandText, (SqlParameter[])null);
1362         }
1363 
1364         /// <summary>
1365         /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction. 
1366         /// </summary>
1367         /// <remarks>
1368         /// e.g.:  
1369         ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
1370         /// </remarks>
1371         /// <param name="transaction">a valid SqlTransaction</param>
1372         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1373         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1374         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1375         public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
1376         {
1377             //pass through the call providing null for the set of SqlParameters
1378             return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
1379         }
1380 
1381         /// <summary>
1382         /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
1383         /// using the provided parameters.
1384         /// </summary>
1385         /// <remarks>
1386         /// e.g.:  
1387         ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
1388         /// </remarks>
1389         /// <param name="transaction">a valid SqlTransaction</param>
1390         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1391         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1392         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1393         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1394         public static object ExecuteScalar(SqlTransaction transaction, string commandText, params SqlParameter[] commandParameters)
1395         {
1396             return ExecuteScalar(transaction, CommandType.Text, commandText, commandParameters);
1397         }
1398 
1399         /// <summary>
1400         /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
1401         /// using the provided parameters.
1402         /// </summary>
1403         /// <remarks>
1404         /// e.g.:  
1405         ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
1406         /// </remarks>
1407         /// <param name="transaction">a valid SqlTransaction</param>
1408         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1409         /// <param name="commandText">the stored procedure name or T-SQL command</param>
1410         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1411         /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
1412         public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1413         {
1414             if (transaction == null)
1415             {
1416                 //create & open a SqlConnection, and dispose of it after we are done.
1417                 using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
1418                 {
1419                     cn.Open();
1420 
1421                     //call the overload that takes a connection in place of the connection string
1422                     return ExecuteScalar(cn, commandType, commandText, commandParameters);
1423                 }
1424             }
1425             else
1426             {
1427                 //create a command and prepare it for execution
1428                 SqlCommand cmd = new SqlCommand();
1429                 PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
1430 
1431                 //execute the command & return the results
1432                 object retval = cmd.ExecuteScalar();
1433 
1434                 // detach the SqlParameters from the command object, so they can be used again.
1435                 cmd.Parameters.Clear();
1436                 return retval;
1437             }
1438         }
1439 
1440         #endregion ExecuteScalar
1441 
1442         #region ExecuteXmlReader
1443 
1444         /// <summary>
1445         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
1446         /// </summary>
1447         /// <remarks>
1448         /// e.g.:  
1449         ///  XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders");
1450         /// </remarks>
1451         /// <param name="connection">a valid SqlConnection</param>
1452         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1453         /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
1454         /// <returns>an XmlReader containing the resultset generated by the command</returns>
1455         public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
1456         {
1457             //pass through the call providing null for the set of SqlParameters
1458             return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
1459         }
1460 
1461         /// <summary>
1462         /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
1463         /// using the provided parameters.
1464         /// </summary>
1465         /// <remarks>
1466         /// e.g.:  
1467         ///  XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
1468         /// </remarks>
1469         /// <param name="connection">a valid SqlConnection</param>
1470         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1471         /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
1472         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1473         /// <returns>an XmlReader containing the resultset generated by the command</returns>
1474         public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1475         {
1476             //create a command and prepare it for execution
1477             SqlCommand cmd = new SqlCommand();
1478             PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
1479 
1480             //create the DataAdapter & DataSet
1481             XmlReader retval = cmd.ExecuteXmlReader();
1482 
1483             // detach the SqlParameters from the command object, so they can be used again.
1484             cmd.Parameters.Clear();
1485             if (connection.State == ConnectionState.Open)
1486                 connection.Close();
1487             return retval;
1488 
1489         }
1490 
1491         /// <summary>
1492         /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
1493         /// </summary>
1494         /// <remarks>
1495         /// e.g.:  
1496         ///  XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders");
1497         /// </remarks>
1498         /// <param name="transaction">a valid SqlTransaction</param>
1499         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1500         /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
1501         /// <returns>an XmlReader containing the resultset generated by the command</returns>
1502         public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
1503         {
1504             //pass through the call providing null for the set of SqlParameters
1505             return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
1506         }
1507 
1508         /// <summary>
1509         /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
1510         /// using the provided parameters.
1511         /// </summary>
1512         /// <remarks>
1513         /// e.g.:  
1514         ///  XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
1515         /// </remarks>
1516         /// <param name="transaction">a valid SqlTransaction</param>
1517         /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
1518         /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
1519         /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
1520         /// <returns>an XmlReader containing the resultset generated by the command</returns>
1521         public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
1522         {
1523             //create a command and prepare it for execution
1524             SqlCommand cmd = new SqlCommand();
1525             PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
1526 
1527             //create the DataAdapter & DataSet
1528             XmlReader retval = cmd.ExecuteXmlReader();
1529 
1530             // detach the SqlParameters from the command object, so they can be used again.
1531             cmd.Parameters.Clear();
1532             return retval;
1533 
1534         }
1535 
1536  
1537 
1538         #endregion ExecuteXmlReader
1539 
1540         #region CreateSqlConnection
1541         public static SqlConnection CreateSqlConnection(string connectionString)
1542         {
1543             //create & open a SqlConnection
1544             SqlConnection cn = new SqlConnection(connectionString);
1545             try
1546             {
1547                 cn.Open();
1548             }
1549             catch
1550             {
1551                 //if we fail to return the SqlTransaction, we need to close the connection ourselves
1552                 cn.Close();
1553                 throw;
1554             }
1555             return cn;
1556         }
1557 
1558 
1559         public static SqlConnection CreateSqlConnection()
1560         {
1561             return CreateSqlConnection(ConfigurationManager.AppSettings["ConnString"]);
1562         }
1563         #endregion
1564 
1565         #region ExecuteSqlCommand
1566 
1567         public static SqlCommand ExecuteSqlCommand()
1568         {
1569             return ExecuteSqlCommand("", ConfigurationManager.AppSettings["ConnString"]);
1570         }
1571 
1572         public static SqlCommand ExecuteSqlCommand(string CmdText)
1573         {
1574             return ExecuteSqlCommand(CmdText, ConfigurationManager.AppSettings["ConnString"]);
1575         }
1576 
1577         public static SqlCommand ExecuteSqlCommand(SqlConnection cn)
1578         {
1579             if (cn.State == ConnectionState.Closed || cn.State == ConnectionState.Broken)
1580                 cn.Open();
1581             try
1582             {
1583                 return new SqlCommand("", cn);
1584             }
1585             catch
1586             {
1587                 //if we fail to return the SqlCommand, we need to close the connection ourselves
1588                 cn.Close();
1589                 throw;
1590             }
1591         }
1592 
1593         public static SqlCommand ExecuteSqlCommand(string connectionString, string CmdText)
1594         {
1595             //create & open a SqlConnection
1596             SqlConnection cn = new SqlConnection(connectionString);
1597             cn.Open();
1598 
1599             try
1600             {
1601                 return new SqlCommand(CmdText, cn);
1602             }
1603             catch
1604             {
1605                 //if we fail to return the SqlCommand, we need to close the connection ourselves
1606                 cn.Close();
1607                 throw;
1608             }
1609         }
1610 
1611         #endregion
1612     }
1613 
1614 }

ListBaseDataSet.cs实例如下:

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Data;
 6 using QuestionsDbSLModel;
 7 
 8 namespace QuestionsDbSL.Web.ClientBin
 9 {
10     /// <summary>
11     /// 用于进行通用数据转化的类
12     /// 将数据库中取出的数据通过 webserice传到SL端
13     /// </summary>
14     public class ListBaseDataSet
15     {
16         /// <summary>
17         /// 按列的次序,将值依次转换到ListBaseVar中
18         /// 按记录条数,将记录压到列表中
19         /// </summary>
20         /// <param name="p_DataSet"></param>
21         /// <param name="p_TableIndex"></param>
22         /// <returns></returns>
23         public static List<BaseVars> DataSetToListBaseVars(DataSet p_DataSet, int p_TableIndex)
24         {
25             if (p_DataSet == null || p_DataSet.Tables.Count < 0)
26                 return null;
27             if (p_TableIndex > p_DataSet.Tables.Count - 1)
28                 return null;
29             if (p_TableIndex < 0)
30                 p_TableIndex = 0;
31 
32             DataTable p_Data = p_DataSet.Tables[p_TableIndex];
33             List<BaseVars> result = new List<BaseVars>();
34             lock (p_Data)
35             {   
36                 for (int j = 0; j < p_Data.Rows.Count; j++)
37                 {
38                     BaseVars lbv = new BaseVars();
39                     for (int k = 0; k < p_Data.Columns.Count; k++)
40                     {
41                         if (p_Data.Rows[j][k].GetType() == typeof(string))
42                         {
43                             lbv.ListString.Add(p_Data.Rows[j][k].ToString());
44                         }
45                         else if (p_Data.Rows[j][k].GetType() == typeof(int))
46                         {
47                             lbv.ListInt.Add((int)(p_Data.Rows[j][k]));
48                         }
49                         else if (p_Data.Rows[j][k].GetType() == typeof(bool))
50                         {
51                             lbv.ListBool.Add((bool)(p_Data.Rows[j][k]));
52                         }
53                         else if (p_Data.Rows[j][k].GetType() == typeof(byte))
54                         {
55                             lbv.ListByte.Add((byte)(p_Data.Rows[j][k]));
56                         }
57                         else if (p_Data.Rows[j][k].GetType() == typeof(float))
58                         {
59                             lbv.ListFloat.Add((float)(p_Data.Rows[j][k]));
60                         }
61                         else if (p_Data.Rows[j][k].GetType() == typeof(double))
62                         {
63                             lbv.ListDouble.Add((double)(p_Data.Rows[j][k]));
64                         }
65                     }
66 
67                     result.Add(lbv);
68                 }
69             }
70             return result;
71         }
72     }
73 }

 

posted on 2013-04-26 11:50  loyung  阅读(336)  评论(0编辑  收藏  举报