MyException - 我的异常网
当前位置:我的异常网» C# » 求1性能较好的c#数据库操作类

求1性能较好的c#数据库操作类(3)

www.MyException.Cn  网友分享于:2013-12-20  浏览:45次

{
//
// TODO: 在此处添加构造函数逻辑
//
}

public DataBaseOperate(
string sConnectionString)
{
if (sConnectionString != " ")
{
m_sConnectionString = sConnectionString;
m_bConnected = false;
}
m_bTransaction = false;
}

/// <summary>
/// 连接数据库,并打开数据库连接
/// </summary>
/// <returns> 成功返回true </returns>
private bool ConnectDataBase()
{
if (!m_bConnected)
{
try
{
if (m_sqlConnection == null)
{
m_sqlConnection = new SqlConnection(m_sConnectionString);
m_sqlConnection.Open();
}

if (m_sqlCommand == null)
{
m_sqlCommand = new SqlCommand();
}
m_bConnected = true;
m_sqlCommand.Connection = m_sqlConnection;
}
catch(SqlException e)
{
throw e;
}
}
return true;
}

/// <summary>
/// 关闭数据库,释放数据库资源
/// </summary>
/// <returns> 成功返回true </returns>
public bool CloseDataBase()
{
Dispose();
return true;
}

/// <summary>
/// 执行数据库查询操作
/// </summary>
/// <param name= "sQuery "> 查询的Sql语句 </param>
/// <param name= "sTableName "> 返回数据集的表名 </param>
/// <returns> 返回数据集 </returns>
public DataSet Search(
string sQuery,
string sTableName )
{

//若连接数据库失败抛出错误
if (!ConnectDataBase())
{
throw(new ApplicationException( "没有建立数据库连接。 "));
}

DataSet dataSet = new DataSet();
m_sqlCommand.CommandType = System.Data.CommandType.Text;
m_sqlCommand.CommandText = sQuery;
m_sqlDataAdapter = new SqlDataAdapter();
m_sqlDataAdapter.SelectCommand = m_sqlCommand;
try
{
m_sqlDataAdapter.Fill(
dataSet,
sTableName);
}
catch(SqlException e)
{
//如果正在执行事务,回滚
if(m_bTransaction)
{
m_sqlTransaction.Rollback();
}
throw e;
}
return dataSet;
}


/// <summary>
/// 执行修改数据库操作,修改、删除等无返回值的操作
/// </summary>
/// <param name= "sSql "> 执行的SQL语句 </param>
/// <returns> 成功执行返回True </returns>
public bool Execute(
string sSql)
{

if (!ConnectDataBase())
{
throw(new ApplicationException( "没有建立数据库连接 "));
}

m_sqlCommand.CommandType = System.Data.CommandType.Text;
m_sqlCommand.CommandText = sSql;
try
{
m_sqlCommand.ExecuteNonQuery();
}
catch(SqlException e)
{
//如果正在执行事务,回滚
if(m_bTransaction)
{
m_sqlTransaction.Rollback();
}
throw e;
}
return true;
}

/// <summary>
/// 开始事务处理功能,之后执行的全部数据库操作语句需要调用提交函数(commit)生效
/// </summary>
public void StartTransation()
{
//若连接数据库失败抛出错误
if (!ConnectDataBase())
{
throw(new ApplicationException( "没有建立数据库连接。 "));
}

m_bTransaction = true;
m_sqlTransaction = m_sqlConnection.BeginTransaction(
IsolationLevel.ReadCommitted);
m_sqlCommand.Transaction = m_sqlTransaction;

}

/// <summary>

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有