ASP.NET中一般都是使用SQL Server作为后台数据库。一般的ASP.NET数据库操作示例程序都是使用单独的数据访问,就是说每个页面都写连接到数据库,存取数据,关闭数据库的代码。这种方式带来了一些弊端,一个就是如果你的数据库改变了,你必须一个页面一个页面的去更改数据库连接代码。第二个弊端就是代码冗余,很多代码都是重复的,不必要的。因此,我试图通过一种一致的数据库操作类来实现ASP.NET种的数据访问,现写出来希望哪位大虾帮助指正!
.net数据库操作类代码:
调用及使用此类的方法:
1.引用此命名空间DataOperate
2.根据需要创建对应的对象
3.根据需要调用此类中相应的方法
.net数据库操作类代码:
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
namespace DataOperate
{
/// <summary>
/// DataAccess 的摘要说明。
/// </summary>
public class DataAccess
{
protected SqlCommand Comm;
protected SqlDataAdapter Adap;
protected SqlConnection Conn; //SQL连接
private string _connectString; //连接串
private string _commandString; //SQL命令
private Hashtable _dict, _result,_mapTable;
private DataSet _ds; //返回结果数据集
private DataRow _recordSet; //纪录集
private string _tableName; //表名
private int _recordCount; //纪录集的行数
private bool _eOF; //结果集是否为空,是否已经到了结尾
private string DB;
private string _deleteOP;
private string _path;
private StreamWriter SWCreate,SWApp;
private string _errorMessage;
private bool _writeLog;
///属性集
/// <summary>
/// 出错信息
/// </summary>
public string ErrorMessage
{
get { return this._errorMessage; }
set { this._errorMessage = value; }
}
/// <summary>
/// 设置或者取得删除的操作者
/// </summary>
public string DeleteOP
{
get { return this._deleteOP; }
set { this._deleteOP = value; }
}
/// <summary>
/// 取得是否溢出
/// </summary>
public bool EOF
{
get { return this._eOF; }
set { this._eOF = value;}
}
/// <summary>
/// 取得执行语句后得出的纪录条数
/// </summary>
public int RecordCount
{
get { return this._recordCount; }
set { this._recordCount = value; }
}
/// <summary>
/// 数据库中的表名
/// </summary>
public string TableName
{
get { return this._tableName; }
set { this._tableName = value; }
}
/// <summary>
/// 返回的记录集
/// </summary>
public DataRow RecordSet
{
get { return this._recordSet; }
set { this._recordSet = value; }
}
/// <summary>
/// 返回的数据集
/// </summary>
public DataSet DS
{
get { return this._ds; }
set { this._ds = value; }
}
/// <summary>
/// 字段和控件的映射表
/// </summary>
public Hashtable MapTable
{
get { return this._mapTable; }
set { this._mapTable = value; }
}
/// <summary>
/// 修改数据时,作为修改结果
/// </summary>
public Hashtable Result
{
get { return this._result; }
set { this._result = value;}
}
/// <summary>
/// 保存数据用的字段和值对应的哈希表,修改数据时用作条件
/// </summary>
public Hashtable Dict
{
get { return this._dict;}
set { this._dict = value;}
}
/// <summary>
/// 查询语句
/// </summary>
public string CommandString
{
get { return this._commandString;}
set { this._commandString = value;}
}
/// <summary>
/// 连接串
/// </summary>
public string ConnectString
{
get { return this._connectString;}
set { this._connectString = value;}
}
///DataAccess的构造函数
/// <summary>
/// 空构造函数
/// </summary>
public DataAccess()
{
ConnectString = System.Configuration.ConfigurationSettings.AppSettings["GZPI"];
Conn = new System.Data.SqlClient.SqlConnection(ConnectString);
if(System.Configuration.ConfigurationSettings.AppSettings["WriteLog"]=="true")
{
_writeLog = true;
}
else
{
_writeLog = false;
}
}
~DataAccess()
{
}
/// <summary>
/// DataAccess的构造函数
/// </summary>
/// <param name="DB1">要访问的数据库名,Web.config里设置的连接字符串对应的key</param>
/// <param name="TableName1">要访问的数据表名</param>
public DataAccess(string DB1,string TableName1)
{
this.ErrorMessage = "";
DB = DB1;
TableName = TableName1;
try
{
ConnectString = System.Configuration.ConfigurationSettings.AppSettings[DB1];
if(System.Configuration.ConfigurationSettings.AppSettings["WriteLog"]=="true")
{
_writeLog = true;
}
else
{
_writeLog = false;
}
Conn = new System.Data.SqlClient.SqlConnection(ConnectString);
Dict = new Hashtable();
Result = new Hashtable();
MapTable = new Hashtable();
DS = new DataSet();
// IS_Open = false;
_path = "C:\\WebDebug.log";
if(_writeLog)
{
if(!File.Exists(_path))
{
using(SWCreate = File.CreateText(_path))
{
SWCreate.WriteLine(" ");
SWCreate.Close();
}
}
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine(" ");
}
}
}
catch(Exception e)
{
this.ErrorMessage = e.ToString();
}
}
/// <summary>
/// DataAccess的构造函数
/// </summary>
/// <param name="CST">数据库的连接字符串</param>
/// <param name="TableName1">要访问的数据表名</param>
/// <param name="flag">是否初始化</param>
public DataAccess(string CST,string TableName1,bool flag)
{
if(flag==true)
{
this.ErrorMessage = "";
TableName = TableName1;
try
{
if(System.Configuration.ConfigurationSettings.AppSettings["WriteLog"]=="true")
{
_writeLog = true;
}
else
{
_writeLog = false;
}
ConnectString = CST;
Conn = new System.Data.SqlClient.SqlConnection(ConnectString);
Dict = new Hashtable();
Result = new Hashtable();
MapTable = new Hashtable();
DS = new DataSet();
_path = "C:\\WebDebug.log";
if(_writeLog)
{
if(!File.Exists(_path))
{
using(SWCreate = File.CreateText(_path))
{
SWCreate.WriteLine(" ");
SWCreate.Close();
}
}
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine(" ");
}
}
}
catch(Exception e)
{
this.ErrorMessage = e.ToString();
}
}
}
///扩展的取数据集,执行SQL的方法
/// <summary>
/// 执行无返回结果的SQL
/// </summary>
/// <param name="strSQL"></param>
public int ExecuteNonQuery(string strSQL)
{
int re = 0;
Conn.Open();
Comm = new SqlCommand(strSQL,Conn);
Comm.CommandTimeout = 60;
try
{
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] CommandString = " + strSQL);
SWApp.Close();
}
}
re = Comm.ExecuteNonQuery();
this.Conn.Close();
}
catch(Exception e)
{
this.Conn.Close();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] Error Message : " + e.ToString());
}
}
this.ErrorMessage = e.ToString();
throw new Exception(e.ToString());
}
return re;
}
/// <summary>
/// 返回查询结果的第一行第一列的值
/// </summary>
/// <param name="strSQL"></param>
/// <returns></returns>
public object ExecuteScalar(string strSQL)
{
Conn.Open();
Comm = new SqlCommand(strSQL,Conn);
Comm.CommandTimeout = 60;
try
{
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] CommandString = " + strSQL);
SWApp.Close();
}
}
object objResutl = Comm.ExecuteScalar();
this.Conn.Close();
return objResutl;
}
catch(Exception e)
{
this.Conn.Close();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] Error Message : " + e.ToString());
}
}
this.ErrorMessage = e.ToString();
throw new Exception(e.ToString());
}
}
/// <summary>
/// 获得查询后得出的数据集
/// </summary>
public DataSet ExecuteDataSet(string strSQL)
{
DataSet ds = new DataSet();
try
{
Conn.Open();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Begin Get DataSet.");
SWApp.WriteLine("CommandString = " + strSQL);
SWApp.Close();
}
}
try
{
Adap = new SqlDataAdapter();
Adap.SelectCommand = new SqlCommand(strSQL,this.Conn);
Adap.SelectCommand.CommandTimeout = 60;
Adap.Fill(ds);
this.Adap.Dispose();
}
catch(Exception e)
{
this.Adap.Dispose();
this.ErrorMessage = e.ToString();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Error Message: " + e.ToString());
}
}
throw new Exception(e.ToString());
}
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> End of Getting DataSet.");
SWApp.Close();
}
}
}
finally
{
Conn.Close();
}
return ds;
}
/// <summary>
/// 获得查询后得出的数据集
/// </summary>
public DataTable ExecuteDataTable(string strSQL)
{
return ExecuteDataSet(strSQL).Tables[0];
}
/// <summary>
/// 执行带参数的存储过程
/// </summary>
/// <param name="aryParameter">参数列表</param>
/// <param name="strProduceName">存储过程名称</param>
public void ExecuteProcedure(ref SqlParameter[] aryParameter,string strProduceName)
{
Conn.Open();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Begin Get DataSet.");
SWApp.WriteLine("CommandString = Exec" + strProduceName);
SWApp.Close();
}
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = Conn;
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.CommandText = strProduceName;
for(int i = 0;i< aryParameter.Length;i++)
{
if (aryParameter[i].Value == null)
{
aryParameter[i].Value = System.DBNull.Value;
}
sqlCmd.Parameters.Add(aryParameter[i]);
}
try
{
sqlCmd.ExecuteNonQuery();
}
catch(Exception ex)
{
this.ErrorMessage = ex.ToString();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Error Message: " + ex.ToString());
}
}
throw new Exception(ex.ToString());
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> End of Getting DataSet.");
SWApp.Close();
}
}
}
sqlCmd.Dispose();
Conn.Close();
}
}
}
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
namespace DataOperate
{
/// <summary>
/// DataAccess 的摘要说明。
/// </summary>
public class DataAccess
{
protected SqlCommand Comm;
protected SqlDataAdapter Adap;
protected SqlConnection Conn; //SQL连接
private string _connectString; //连接串
private string _commandString; //SQL命令
private Hashtable _dict, _result,_mapTable;
private DataSet _ds; //返回结果数据集
private DataRow _recordSet; //纪录集
private string _tableName; //表名
private int _recordCount; //纪录集的行数
private bool _eOF; //结果集是否为空,是否已经到了结尾
private string DB;
private string _deleteOP;
private string _path;
private StreamWriter SWCreate,SWApp;
private string _errorMessage;
private bool _writeLog;
///属性集
/// <summary>
/// 出错信息
/// </summary>
public string ErrorMessage
{
get { return this._errorMessage; }
set { this._errorMessage = value; }
}
/// <summary>
/// 设置或者取得删除的操作者
/// </summary>
public string DeleteOP
{
get { return this._deleteOP; }
set { this._deleteOP = value; }
}
/// <summary>
/// 取得是否溢出
/// </summary>
public bool EOF
{
get { return this._eOF; }
set { this._eOF = value;}
}
/// <summary>
/// 取得执行语句后得出的纪录条数
/// </summary>
public int RecordCount
{
get { return this._recordCount; }
set { this._recordCount = value; }
}
/// <summary>
/// 数据库中的表名
/// </summary>
public string TableName
{
get { return this._tableName; }
set { this._tableName = value; }
}
/// <summary>
/// 返回的记录集
/// </summary>
public DataRow RecordSet
{
get { return this._recordSet; }
set { this._recordSet = value; }
}
/// <summary>
/// 返回的数据集
/// </summary>
public DataSet DS
{
get { return this._ds; }
set { this._ds = value; }
}
/// <summary>
/// 字段和控件的映射表
/// </summary>
public Hashtable MapTable
{
get { return this._mapTable; }
set { this._mapTable = value; }
}
/// <summary>
/// 修改数据时,作为修改结果
/// </summary>
public Hashtable Result
{
get { return this._result; }
set { this._result = value;}
}
/// <summary>
/// 保存数据用的字段和值对应的哈希表,修改数据时用作条件
/// </summary>
public Hashtable Dict
{
get { return this._dict;}
set { this._dict = value;}
}
/// <summary>
/// 查询语句
/// </summary>
public string CommandString
{
get { return this._commandString;}
set { this._commandString = value;}
}
/// <summary>
/// 连接串
/// </summary>
public string ConnectString
{
get { return this._connectString;}
set { this._connectString = value;}
}
///DataAccess的构造函数
/// <summary>
/// 空构造函数
/// </summary>
public DataAccess()
{
ConnectString = System.Configuration.ConfigurationSettings.AppSettings["GZPI"];
Conn = new System.Data.SqlClient.SqlConnection(ConnectString);
if(System.Configuration.ConfigurationSettings.AppSettings["WriteLog"]=="true")
{
_writeLog = true;
}
else
{
_writeLog = false;
}
}
~DataAccess()
{
}
/// <summary>
/// DataAccess的构造函数
/// </summary>
/// <param name="DB1">要访问的数据库名,Web.config里设置的连接字符串对应的key</param>
/// <param name="TableName1">要访问的数据表名</param>
public DataAccess(string DB1,string TableName1)
{
this.ErrorMessage = "";
DB = DB1;
TableName = TableName1;
try
{
ConnectString = System.Configuration.ConfigurationSettings.AppSettings[DB1];
if(System.Configuration.ConfigurationSettings.AppSettings["WriteLog"]=="true")
{
_writeLog = true;
}
else
{
_writeLog = false;
}
Conn = new System.Data.SqlClient.SqlConnection(ConnectString);
Dict = new Hashtable();
Result = new Hashtable();
MapTable = new Hashtable();
DS = new DataSet();
// IS_Open = false;
_path = "C:\\WebDebug.log";
if(_writeLog)
{
if(!File.Exists(_path))
{
using(SWCreate = File.CreateText(_path))
{
SWCreate.WriteLine(" ");
SWCreate.Close();
}
}
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine(" ");
}
}
}
catch(Exception e)
{
this.ErrorMessage = e.ToString();
}
}
/// <summary>
/// DataAccess的构造函数
/// </summary>
/// <param name="CST">数据库的连接字符串</param>
/// <param name="TableName1">要访问的数据表名</param>
/// <param name="flag">是否初始化</param>
public DataAccess(string CST,string TableName1,bool flag)
{
if(flag==true)
{
this.ErrorMessage = "";
TableName = TableName1;
try
{
if(System.Configuration.ConfigurationSettings.AppSettings["WriteLog"]=="true")
{
_writeLog = true;
}
else
{
_writeLog = false;
}
ConnectString = CST;
Conn = new System.Data.SqlClient.SqlConnection(ConnectString);
Dict = new Hashtable();
Result = new Hashtable();
MapTable = new Hashtable();
DS = new DataSet();
_path = "C:\\WebDebug.log";
if(_writeLog)
{
if(!File.Exists(_path))
{
using(SWCreate = File.CreateText(_path))
{
SWCreate.WriteLine(" ");
SWCreate.Close();
}
}
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine(" ");
}
}
}
catch(Exception e)
{
this.ErrorMessage = e.ToString();
}
}
}
///扩展的取数据集,执行SQL的方法
/// <summary>
/// 执行无返回结果的SQL
/// </summary>
/// <param name="strSQL"></param>
public int ExecuteNonQuery(string strSQL)
{
int re = 0;
Conn.Open();
Comm = new SqlCommand(strSQL,Conn);
Comm.CommandTimeout = 60;
try
{
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] CommandString = " + strSQL);
SWApp.Close();
}
}
re = Comm.ExecuteNonQuery();
this.Conn.Close();
}
catch(Exception e)
{
this.Conn.Close();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] Error Message : " + e.ToString());
}
}
this.ErrorMessage = e.ToString();
throw new Exception(e.ToString());
}
return re;
}
/// <summary>
/// 返回查询结果的第一行第一列的值
/// </summary>
/// <param name="strSQL"></param>
/// <returns></returns>
public object ExecuteScalar(string strSQL)
{
Conn.Open();
Comm = new SqlCommand(strSQL,Conn);
Comm.CommandTimeout = 60;
try
{
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] CommandString = " + strSQL);
SWApp.Close();
}
}
object objResutl = Comm.ExecuteScalar();
this.Conn.Close();
return objResutl;
}
catch(Exception e)
{
this.Conn.Close();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "] Error Message : " + e.ToString());
}
}
this.ErrorMessage = e.ToString();
throw new Exception(e.ToString());
}
}
/// <summary>
/// 获得查询后得出的数据集
/// </summary>
public DataSet ExecuteDataSet(string strSQL)
{
DataSet ds = new DataSet();
try
{
Conn.Open();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Begin Get DataSet.");
SWApp.WriteLine("CommandString = " + strSQL);
SWApp.Close();
}
}
try
{
Adap = new SqlDataAdapter();
Adap.SelectCommand = new SqlCommand(strSQL,this.Conn);
Adap.SelectCommand.CommandTimeout = 60;
Adap.Fill(ds);
this.Adap.Dispose();
}
catch(Exception e)
{
this.Adap.Dispose();
this.ErrorMessage = e.ToString();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Error Message: " + e.ToString());
}
}
throw new Exception(e.ToString());
}
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> End of Getting DataSet.");
SWApp.Close();
}
}
}
finally
{
Conn.Close();
}
return ds;
}
/// <summary>
/// 获得查询后得出的数据集
/// </summary>
public DataTable ExecuteDataTable(string strSQL)
{
return ExecuteDataSet(strSQL).Tables[0];
}
/// <summary>
/// 执行带参数的存储过程
/// </summary>
/// <param name="aryParameter">参数列表</param>
/// <param name="strProduceName">存储过程名称</param>
public void ExecuteProcedure(ref SqlParameter[] aryParameter,string strProduceName)
{
Conn.Open();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Begin Get DataSet.");
SWApp.WriteLine("CommandString = Exec" + strProduceName);
SWApp.Close();
}
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = Conn;
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.CommandText = strProduceName;
for(int i = 0;i< aryParameter.Length;i++)
{
if (aryParameter[i].Value == null)
{
aryParameter[i].Value = System.DBNull.Value;
}
sqlCmd.Parameters.Add(aryParameter[i]);
}
try
{
sqlCmd.ExecuteNonQuery();
}
catch(Exception ex)
{
this.ErrorMessage = ex.ToString();
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> Error Message: " + ex.ToString());
}
}
throw new Exception(ex.ToString());
if(_writeLog)
{
using(SWApp = File.AppendText(_path))
{
SWApp.WriteLine("[" + DateTime.Now.ToString() + "]==> End of Getting DataSet.");
SWApp.Close();
}
}
}
sqlCmd.Dispose();
Conn.Close();
}
}
}
调用及使用此类的方法:
1.引用此命名空间DataOperate
2.根据需要创建对应的对象
3.根据需要调用此类中相应的方法