//用SqlDataAdapter填充DataSet和更新数据库 private SqlCommand cmd = new SqlCommand(); private SqlDataReader sdr = null; private SqlDataAdapter sda = null; private SqlCommandBuilder scb = null; private DataSet ds = null; #region ExecuteApdater 使用SQL查询语句填充一个DataSet并返回 /// <summary> /// 使用SQL查询语句填充一个DataSet并返回 /// </summary> /// <param name="cmdType">命令类型</param> /// <param name="cmdText">SQL语句字符串</param> /// <param name="tableName">指定表名(不指定表名时传null)</param> /// <param name="parms">参数集合(没有参数时传null)</param> /// <returns>DataSet</returns> public DataSet ExecuteApdater(CommandType cmdType, string cmdText, string tableName, SqlParameter[] parms) { ds = new DataSet(); try { PrepareCommand(cmdType, cmdText, null, null); sda = new SqlDataAdapter(); sda.SelectCommand = cmd; scb = new SqlCommandBuilder(sda); if (tableName != null) { sda.Fill(ds, tableName); return ds; } sda.Fill(ds); return ds; } catch (Exception ex) { throw ex; } } public void ExecuteAdapterUpdate(string tableName) { try { sda.Update(ds.Tables[tableName]); } catch (Exception ex) { throw ex; } } #endregion #region PrepareCommand 命令预处理 为SqlCommand设置属性 /// <summary> /// 命令预处理 为SqlCommand设置属性 /// </summary> /// <param name="cmdType">命令类型</param> /// <param name="cmdText">SQL语句查询字符串</param> /// <param name="parms">参数集合(没有参数时传null)</param> /// <param name="trans">事务</param> private void PrepareCommand(CommandType cmdType, string cmdText, SqlParameter[] parms, SqlTransaction trans) { cmd.Connection = GetConn(); cmd.CommandText = cmdText; cmd.CommandType = cmdType; if (trans != null) cmd.Transaction = trans; if (parms != null) { foreach (SqlParameter parm in parms) cmd.Parameters.Add(parm); //cmd.Parameters.AddRange(parms); } } #endregion