using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
namespace H3C.RD.IPDPlan.Common
{
public class SqlContext : DisposableObject
{
private readonly string _connectionString;
//private IConfiguration Configuration;
private string defaultConnName = "数据库连接字符串key";
public SqlContext()
{
this._connectionString = System.Configuration.ConfigurationManager.AppSettings[defaultConnName];
InitConnection();
}
public SqlContext(string ConnName)
{
// TODO: Complete member initialization
this._connectionString = System.Configuration.ConfigurationManager.AppSettings[ConnName];
InitConnection();
}
public SqlConnection Conn { private set; get; }
public void InitConnection()
{
this.Conn = new SqlConnection(this._connectionString);
}
private bool _committed = true;
public bool Committed
{
set { _committed = value; }
get { return _committed; }
}
public SqlTransaction Tran { private set; get; }
public void Open()
{
if (this.Conn.State != ConnectionState.Open)
this.Conn.Open();
this.Committed = true;
}
public void BeginTran()
{
if (this.Conn.State != ConnectionState.Open)
this.Conn.Open();
this.Tran = this.Conn.BeginTransaction();
this.Committed = false;
}
public void BeginTran(IsolationLevel il)
{
if (this.Conn.State != ConnectionState.Open)
this.Conn.Open();
this.Tran = this.Conn.BeginTransaction(il);
this.Committed = false;
}
public void Commit()
{
if (Committed) return;
this.Tran.Commit();
this.Conn.Close();
this._committed = true;
}
public void Rollback()
{
if (Committed) return;
this.Tran.Rollback();
this.Conn.Close();
this._committed = true;
}
public void Close()
{
if (this.Conn.State == ConnectionState.Open)
this.Conn.Close();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
if (this.Conn.State != ConnectionState.Open) return;
Commit();
this.Conn.Close();
this.Conn.Dispose();
}
}
public abstract class DisposableObject : IDisposable
{
#region Finalization Constructs
/// <summary>
/// Finalizes the object.
/// </summary>
~DisposableObject()
{
this.Dispose(false);
}
#endregion
#region Protected Methods
/// <summary>
/// Disposes the object.
/// </summary>
/// <param name="disposing">A <see cref="System.Boolean"/> value which indicates whether
/// the object should be disposed explicitly.</param>
protected abstract void Dispose(bool disposing);
/// <summary>
/// Provides the facility that disposes the object in an explicit manner,
/// preventing the Finalizer from being called after the object has been
/// disposed explicitly.
/// </summary>
protected void ExplicitDispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.ExplicitDispose();
}
#endregion
}
}