using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// DataBase 的摘要说明
/// </summary>
public class DataBase
{
protected SqlConnection Connection;
protected string ConnectionString;
public DataBase()
{
//
// TODO: 在此处添加构造函数逻辑
//
ConnectionString = ConfigurationManager.AppSettings["DBConnectionString"];
}
~DataBase()
{
try
{
if (Connection != null)
Connection.Close();
}
catch { }
try
{
Dispose();
}
catch { }
}
public void Dispose()
{
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
protected void Open()
{
if (Connection == null)
{
Connection = new SqlConnection(ConnectionString);
}
if (Connection.State.Equals(ConnectionState.Closed))
{
Connection.Open();
}
}
public void Close()
{
if (Connection != null)
Connection.Close();
}
public int ExecuteSQL(String SqlString)
{
int count = -1;
Open();
try
{
SqlCommand cmd = new SqlCommand(SqlString, Connection);
count = cmd.ExecuteNonQuery();
}
catch
{
count = 1;
}
finally
{
Close();
}
return count;
}
public DataSet GetDataSet(String SqlString)
{
Open();
SqlDataAdapter adaptder = new SqlDataAdapter(SqlString, Connection);
DataSet dataset = new DataSet();
adaptder.Fill(dataset);
Close();
return dataset;
}
public DataRow GetDataRow(String SqlString)
{
DataSet dataset = GetDataSet(SqlString);
dataset.CaseSensitive = false;
if (dataset.Tables[0].Rows.Count > 0)
{
return dataset.Tables[0].Rows[0];
}
else
{
return null;
}
}
public bool ExecuteSQL(ArrayList SqlStrings)
{
bool success = true;
Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction trans = Connection.BeginTransaction();
cmd.Connection = Connection;
cmd.Transaction = trans;
try
{
foreach (String str in SqlStrings)
{
cmd.CommandText = str;
cmd.ExecuteNonQuery();
}
trans.Commit();
}
catch
{
success = false;
trans.Rollback();
}
finally
{
Close();
}
return success;
}
public SqlDataReader GetDataReader(String SqlString)
{
Open();
SqlCommand cmd = new SqlCommand(SqlString, Connection);
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
public bool Insert(String TableName,Hashtable Cols)
{
int Count =0;
if (Cols.Count<=0)
{
return true;
}
String Fields ="(";
String Values="Values(";
foreach(DictionaryEntry item in Cols)
{
if(Count!=0)
{
Fields+=",";
Values+=",";
}
Fields+=item.Key.ToString();
Values+=item.Value.ToString();
Count++;
}
Fields+=")";
Values+=")";
String SqlString = "Insert into " + TableName + Fields + Values;
return Convert.ToBoolean(ExecuteSQL(SqlString));
}
public bool Update(String TableName, Hashtable Cols, String Where)
{
int Count = 0;
if (Cols.Count <= 0)
{
return true;
}
String Fields = " ";
foreach (DictionaryEntry item in Cols)
{
if (Count != 0)
{
Fields += ",";
}
Fields += item.Key.ToString();
Fields += "=";
Fields += item.Value.ToString();
Count++;
}
Fields += " ";
String SqlString = "Update " + TableName + " Set " + Fields + Where;
return Convert.ToBoolean(ExecuteSQL(SqlString));
}
}