我一直在尝试为一个小项目编写一个 sql 连接类,它将使用简单的 sql 命令进行插入/更新/选择/删除操作,有时还有事务,有什么指导方针我可以使用吗?可以在有或没有事务的任何时候实例化该类...
试过:
public class DbConnection
{
public static string srConnectionString = "blablab";
public DbConnection()
{
}
public static DataSet db_Select_Query(string strQuery)
{
DataSet dataSet = new DataSet();
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(strQuery, connection);
DA.Fill(dataSet);
}
return dataSet;
}
catch (Exception)
{
//some error handling.
}
}
public static void db_Update_Delete_Query(string strQuery)
{
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(strQuery, connection);
command.ExecuteNonQuery();
}
}
catch (Exception)
{
//some error handling.
}
}
例如,只要使用此类,我如何添加打开或关闭事务的参数?例如,我可以从类外部调用 db.commit 或 db.rollback。
PS:尝试了一些微指令(例如 petapoco),有没有办法用纯 sql 运行它们并仅将返回类型作为数据集或数据表?
问候。
编辑:
public class dbconnection : IDisposable
{
public static string strConnectionString = @"Data Source=PC137\PC137_SQL2008;Initial Catalog=BARZO;Integrated Security=True";
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
private SqlTransaction transaction;
private SqlConnection connection;
private SqlCommand command = new SqlCommand();
public void db_OpenConnection(bool WithTransaction)
{
connection = new SqlConnection(strConnectionString);
connection.Open();
if (WithTransaction)
{
transaction = connection.BeginTransaction();
}
}
public void db_CloseConnection()
{
connection.Close();
connection.Dispose();
transaction.Dispose();
command.Dispose();
}
public void db_Commit()
{
transaction.Commit();
}
public void db_RollBack()
{
transaction.Rollback();
}
public DataSet db_Select_Query(string strQuery)
{
var dataSet = new DataSet();
try
{
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter(strQuery, connection);
SqlDataAdapter.Fill(dataSet);
return dataSet;
}
catch (SqlException sqlError)
{
MessageBox.Show(sqlError,MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
public bool db_Update_Delete_Query(string strQuery)
{
try
{
command = new SqlCommand(strQuery, connection);
command.Transaction = transaction;
command.ExecuteNonQuery();
}
catch (SqlException sqlError)
{
MessageBox.Show(sqlError,MessageBoxButtons.OK, MessageBoxIcon.Stop);
return false;
}
return true;
}
}