using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
///
///DBacess 的摘要说明
///
namespace basic
{
public class DBacess
{
///
/// 创建活动SqlConnection
///
/// SqlConnection
///
public static SqlConnection con;
private static SqlConnection connection()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
con = conn;
return conn;
}
///
/// 打开连接数据库
///
/// SqlConnection对象
private void OpenConnection(SqlConnection conn)
{
if (conn != null && conn.State == ConnectionState.Closed)
conn.Open();
}
///
/// 关闭数据库
///
/// SqlConnection对象
private void CloseConnection(SqlConnection conn)
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
///
/// 更新数据库
///
///
///
///
///
public bool Update(string sql, SqlParameter[] parameters, CommandType type)
{
SqlConnection conn = connection();
bool result = false;
try
{
using (conn)
{
SqlCommand cmd = new SqlCommand(sql, conn);
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
if (parameters != null && parameter.ParameterName != "")
{
cmd.Parameters.Add(parameter);
}
}
}
cmd.CommandType = type;
cmd.Connection.Open();
int flag = cmd.ExecuteNonQuery();
if (flag > 0)
result = true;
}
}
finally
{
CloseConnection(conn);
}
return result;
}
///
/// 根据条件查询数据
///
///
///
/// DataTable
public DataTable SelectReturnDataTable(string sql, SqlParameter[] parameters)
{
SqlConnection conn = connection();
DataTable dt = new DataTable();
try
{
using (conn)
{
SqlCommand cmd = new SqlCommand(sql, conn);
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
if (parameter != null && parameter.ParameterName != "")
{
cmd.Parameters.Add(parameter);
}
}
}
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
//catch (Exception e)
//{
//}
finally
{
CloseConnection(conn);
}
return dt;
}
///
/// 根据条件查询数据
///
///
///
/// DataSet
public DataSet SelectReturnDataSet(string sql, SqlParameter[] parameters)
{
SqlConnection conn = connection();
DataSet ds = new DataSet();
try
{
using (conn)
{
SqlCommand cmd = new SqlCommand(sql, conn);
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
if (parameter != null && parameter.ParameterName != "")
{
cmd.Parameters.Add(parameter);
}
}
}
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
}
}
//catch (Exception e)
//{
//}
finally
{
CloseConnection(conn);
}
return ds;
}
}
}