好久不接触这些闲暇时间回顾一下以前的基础。因为平常使用的时候都是直接调用SqlDB.dll这个类。先看这个类的结构
纸上得来终觉浅,绝知此事要躬行。个人觉得里面的标准操作就是对数据库增删查改 。特别适合初学者操作数据库,当初我也是那么来的。下面直接贴代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Configuration; using System.Text; namespace FileUpDownThroou { ////// SqlServer访问类 /// public class SqlDB { #region <——————————定义参数——————————> /// /// 数据库链接字符串 /// protected readonly string SqlConning = ConfigurationManager.ConnectionStrings["ConnSqlString"].ConnectionString; /// /// 数据库链接对象 /// private SqlConnection sqlConnection; /// /// 数据库事务对象 /// private SqlTransaction sqlTransaction; /// /// 构造函数创建数据库链接 /// #endregion #region<——————————构造函数——————————> public SqlDB() { if(sqlConnection==null) { sqlConnection = new SqlConnection(SqlConning); sqlConnection.Open(); } } #endregion #region <——————————事务处理——————————> public SqlTransaction SqlTran { get { return sqlTransaction; } set { sqlTransaction = value; } } /// /// 打开数据链接 /// public void OpenConnection() { if(sqlConnection != null && sqlConnection.State != ConnectionState.Open) { sqlConnection.Open(); } } /// /// 关闭数据库链接 /// public void CloseConnection() { if(sqlConnection != null && sqlConnection.State==ConnectionState.Open) { sqlConnection.Close(); } } /// /// 开始一个数据库事务 /// /// 链接的事务锁定行为 public void BeginTransaction(IsolationLevel isolationlevel) { if(sqlConnection.State==ConnectionState.Closed) { sqlConnection.Open(); } try { SqlTran = sqlConnection.BeginTransaction(isolationlevel); } catch(SqlException ex) { throw new Exception(ex.StackTrace); } catch(Exception e) { throw new Exception(e.StackTrace); } } /// /// 开始一个数据库事务 /// public void BeginTransaction() { if (sqlConnection.State == ConnectionState.Closed) { sqlConnection.Open(); } try { SqlTran = sqlConnection.BeginTransaction(); } catch (SqlException ex) { throw new Exception(ex.StackTrace); } catch (Exception e) { throw new Exception(e.StackTrace); } } /// /// 提交一个数据库事务 /// public void CommitTransaction() { try { sqlTransaction.Commit(); CloseConnection(); } catch(SqlException ex) { throw new Exception(ex.StackTrace); } catch(Exception e) { throw new Exception(e.StackTrace); } } /// /// 回退一个数据库事务 /// public void RollBackTransaction() { try { SqlTran.Rollback(); CloseConnection(); } catch (SqlException ex) { throw new Exception(ex.StackTrace); } catch (Exception e) { throw new Exception(e.StackTrace); } } #endregion #region <——————————标准操作——————————> /// /// 执行Sql语句返回SqlDataReader /// /// Sql语句 /// 参数集合 /// 命令类型 /// 查询影响说明 /// 满足条件的SqlDataReader public SqlDataReader ExecuteDataReader(string Sql, List parameters, CommandType commandType, CommandBehavior commandBehavior) { return CreateSqlCommand(Sql, parameters, commandType).ExecuteReader(commandBehavior); } /// /// 执行Sql语句返回SqlDataReader /// /// Sql语句 /// 参数集合 /// 命令类型 /// 满足条件的SqlDataReader public SqlDataReader ExecuteDataReader(string Sql, List parameters, CommandType commandType) { return ExecuteDataReader(Sql, parameters, commandType, CommandBehavior.Default); } /// /// 执行Sql语句返回SqlDataReader /// /// Sql语句 /// 参数集合 /// 满足条件的SqlDataReader public SqlDataReader ExecuteDataReader(string Sql, List parameters) { return ExecuteDataReader(Sql, parameters, CommandType.Text, CommandBehavior.Default); } /// /// 执行Sql语句返回SqlDataReader /// /// Sql语句 /// 满足条件的SqlDataReader public SqlDataReader ExecuteDataReader(string Sql) { return ExecuteDataReader(Sql, null, CommandType.Text, CommandBehavior.Default); } /// /// 执行Sql语句返回单个对象 /// /// Sql语句 /// 参数集合 /// 命令类型 /// 满足条件的单个对象 public object ExecuteScalar(string Sql, List parameters, CommandType commandType) { return CreateSqlCommand(Sql, parameters, commandType).ExecuteScalar(); } /// /// 执行Sql语句返回单个对象 /// /// Sql语句 /// 参数集合 /// 满足条件的单个对象 public object ExecuteScalar(string Sql, List parameters) { return ExecuteScalar(Sql, parameters, CommandType.Text); } /// /// 执行Sql语句返回单个对象 /// /// Sql语句 /// 满足条件的单个对象 public object ExecuteScalar(string Sql) { return ExecuteScalar(Sql, null, CommandType.Text); } /// /// 执行非查询类的Sql语句 /// /// Sql语句 /// 参数集合 /// 命令类型 /// 成功执行所影响的记录数 public int ExecuteNonQuery(string Sql, List parameters, CommandType commandType) { return CreateSqlCommand(Sql, parameters, commandType).ExecuteNonQuery(); } /// /// 执行非查询类的Sql语句z /// /// Sql语句 /// 参数集合 /// 成功执行所影响的记录数 public int ExecuteNonQuery(string Sql, List parameters) { return ExecuteNonQuery(Sql, parameters, CommandType.Text); } /// /// 执行非查询类的Sql语句 /// /// Sql语句 /// 成功执行所影响的记录数 public int ExecuteNonQuery(string Sql) { return ExecuteNonQuery(Sql, null, CommandType.Text); } /// /// 执行Sql语句返回DataTable /// /// Sql语句 /// 参数集合 /// 命令类型 /// DataTable public DataTable ExecuteDataTable(string Sql, List sqlParameters, CommandType commandType) { SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType)); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); return dataTable; } /// /// 执行Sql语句返回DataTable /// /// Sql语句 /// 参数集合 /// DataTable public DataTable ExecuteDataTable(string Sql, List sqlParameters) { return ExecuteDataTable(Sql, sqlParameters, CommandType.Text); } /// /// 执行Sql语句返回DataTable /// /// Sql语句 /// DataTable public DataTable ExecuteDataTable(string Sql) { return ExecuteDataTable(Sql, null, CommandType.Text); } /// /// 执行Sql语句返回DataSet /// /// Sql语句 /// 参数集合 /// 命令类型 /// DataSet public DataSet ExecuteDataSet(string Sql, List sqlParameters, CommandType commandType) { SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType)); DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); return dataSet; } /// /// 执行Sql语句返回DataSet /// /// Sql语句 /// 参数集合 /// DataSet public DataSet ExecuteDataSet(string Sql, List sqlParameters) { return ExecuteDataSet(Sql, sqlParameters, CommandType.Text); } /// /// 执行Sql语句返回DataSet /// /// Sql语句 /// DataSet public DataSet ExecuteDataSet(string Sql) { return ExecuteDataSet(Sql, null, CommandType.Text); } /// /// 执行查询,返回查询的分页结果数据集 /// /// Sql语句 /// 参数集合 /// 命令类型 /// 页索引 /// 每页的记录数 /// 分页结果数据集 public DataSet ExecuteDataSet(string Sql, List sqlParameters, CommandType commandType, int PageIndex, int PageSize) { //设置导入的起始地址 int firstPage = PageIndex * PageSize; SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType)); DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet, firstPage, PageSize, "PranaTable"); return dataSet; } /// /// 执行查询,返回查询的分页结果数据集 /// /// Sql语句 /// 参数集合 /// 页索引 /// 每页的记录数 /// 分页结果数据集 public DataSet ExecuteDataSet(string Sql, List sqlParameters, int PageIndex, int PageSize) { return ExecuteDataSet(Sql, sqlParameters, CommandType.Text, PageIndex, PageSize); } /// /// 执行查询,返回查询的分页结果数据集 /// /// Sql语句 /// 页索引 /// 每页的记录数 /// 分页结果数据集 public DataSet ExecuteDataSet(string Sql, int PageIndex, int PageSize) { return ExecuteDataSet(Sql, null, CommandType.Text, PageIndex, PageSize); } /// /// 创建Sql命令对象 /// /// Sql语句 /// 参数集合 /// 命令类型 /// 成功创建的SqlCommand对象 private SqlCommand CreateSqlCommand(string Sql, List parameters, CommandType commandType) { SqlCommand sqlCommand = new SqlCommand(Sql, sqlConnection, SqlTran); sqlCommand.CommandType = commandType; if (parameters != null) { foreach (SqlParameter parameter in parameters) { sqlCommand.Parameters.Add(parameter); } } return sqlCommand; } #endregion #region <——————————缓存操作——————————> /// /// Hashtable中缓存的参数 /// private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); /// /// 缓存查询的OleDb参数对象. /// /// /// public void CacheParameters(string cacheKey, params SqlParameter[] cmdParms) { parmCache[cacheKey] = cmdParms; } /// /// 从缓存获取指定的参数对象数组. /// /// /// public SqlParameter[] GetCachedParameters(string cacheKey) { SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null) { return null; } SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++) { clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); } return clonedParms; } #endregion #region <——————————增删改查——————————> private static bool haveTransaction = false; public static bool HaveTransaction { get { return haveTransaction; } set { haveTransaction = value; } } /// /// 查询字符串的默认长度 /// private const int defaultCommandTextLength = 256; /// /// 根据表名等参数创建数据库查询语句 /// /// 表名称 /// 返回的记录数 /// 字段名称 /// 条件 /// 排序字段 /// 数据库查询语句 private StringBuilder CreateSqlCommandText(string tableName, int topNum, string field, string condition, string order) { StringBuilder Sql = new StringBuilder(defaultCommandTextLength); Sql.Append("SELECT "); if (topNum > 0) { Sql.AppendFormat("TOP {0} ", topNum); } Sql.AppendFormat("{0} FROM {1} ", field, tableName); if (condition != null && condition.Trim().Length != 0) { Sql.AppendFormat("WHERE {0} ", condition); } if (order != null && order.Trim().Length != 0) { Sql.AppendFormat(" ORDER BY {0}", order); } return Sql; } /// /// 向表中插入数据 /// /// 表名称 /// 字段名称字符串 /// 字段值参数字符串 /// 字段参数集合 /// 成功插入的记录数 public int Insert(string tableName, string field, string fieldValue, List parameters) { try { if (HaveTransaction == false) { OpenConnection(); } StringBuilder Sql = new StringBuilder(defaultCommandTextLength); Sql.AppendFormat("INSERT INTO {0}({1}) VALUES({2});", tableName, field, fieldValue); return ExecuteNonQuery(Sql.ToString(), parameters); } finally { if (HaveTransaction == false) { CloseConnection(); } } } /// /// 从表中删除数据 /// /// 表名称 /// 删除条件 /// 删除条件参数集合 /// 成功删除的记录数 public int Delete(string tableName, string condition, List parameters) { try { if (HaveTransaction == false) { OpenConnection(); } StringBuilder Sql = new StringBuilder(defaultCommandTextLength); Sql.AppendFormat("DELETE FROM {0} ", tableName); if (condition != null && condition.Trim().Length != 0) { Sql.AppendFormat("WHERE {0}", condition); } return ExecuteNonQuery(Sql.ToString(), parameters); } finally { if (HaveTransaction == false) { CloseConnection(); } } } /// /// 根据条件修改表中的数据 /// /// 表名称 /// 字段名城 /// 修改条件 /// 修改参数集合 /// 成功修改的记录数 public int Update(string tableName, string fieldValue, string condition, List parameters) { try { if (HaveTransaction == false) { OpenConnection(); } StringBuilder Sql = new StringBuilder(defaultCommandTextLength); Sql.AppendFormat("UPDATE {0} SET {1} ", tableName, fieldValue); if (condition != null && condition.Trim().Length != 0) { Sql.AppendFormat("WHERE {0}", condition); } return ExecuteNonQuery(Sql.ToString(), parameters); } finally { if (HaveTransaction == false) { CloseConnection(); } } } #endregion } }
里面的每个方法都有注解,应该都看的清楚。增删查改都有不同的重载
就像这个DetSet就有5个重载 用的时候根据需要就可以。
///
/// 执行Sql语句返回DataSet
///
/// Sql语句
/// 参数集合
/// 命令类型
///
public DataSet ExecuteDataSet(string Sql, List
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
return dataSet;
}
///
/// 执行Sql语句返回DataSet
///
/// Sql语句
/// 参数集合
///
public DataSet ExecuteDataSet(string Sql, List
{
return ExecuteDataSet(Sql, sqlParameters, CommandType.Text);
}
///
/// 执行Sql语句返回DataSet
///
/// Sql语句
///
public DataSet ExecuteDataSet(string Sql)
{
return ExecuteDataSet(Sql, null, CommandType.Text);
}
///
/// 执行查询,返回查询的分页结果数据集
///
/// Sql语句
/// 参数集合
/// 命令类型
/// 页索引
/// 每页的记录数
///
public DataSet ExecuteDataSet(string Sql, List
{
//设置导入的起始地址
int firstPage = PageIndex * PageSize;
SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, firstPage, PageSize, "PranaTable");
return dataSet;
}
///
/// 执行查询,返回查询的分页结果数据集
///
/// Sql语句
/// 参数集合
/// 页索引
/// 每页的记录数
///
public DataSet ExecuteDataSet(string Sql, List
{
return ExecuteDataSet(Sql, sqlParameters, CommandType.Text, PageIndex, PageSize);
}
///
/// 执行查询,返回查询的分页结果数据集
///
/// Sql语句
/// 页索引
/// 每页的记录数
///
public DataSet ExecuteDataSet(string Sql, int PageIndex, int PageSize)
{
return ExecuteDataSet(Sql, null, CommandType.Text, PageIndex, PageSize);
}