using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// 数据库操作基类
/// </summary>
public class SqlHelp
{
	private SqlConnection sqlconn;//创建SQL连接
	private SqlCommand cmd;//创建SQL命令对象
	private SqlDataAdapter sda;//创建SQL数据适配器
	private SqlDataReader sdr;//创建SQL数据读取器
	private SqlParameter param;//创建SQL参数
	private DataSet ds;//创建数据集

	/// <summary>
	/// 数据库连接字符串
	/// </summary>
	public readonly string strConn = System.Configuration.ConfigurationManager.AppSettings["strcon"];

	public SqlHelp()
	{
		//
	}

	/// <summary>
	/// 打开数据库的连接
	/// </summary>
	public void Open()
	{
		#region
		sqlconn = new SqlConnection(strConn);
		sqlconn.Open();
		#endregion
	}

	/// <summary>
	/// 关闭数据库连接
	/// </summary>
	public void Close()
	{
		#region
		if (sqlconn != null)
		{
			sqlconn.Close();
			sqlconn.Dispose();
		}
		#endregion
	}

	/// <summary>
	/// 返回DataSet数据集
	/// </summary>
	/// <param name="strSql"></param>
	/// <returns></returns>
	public DataSet GetDs(string strSql)
	{
		#region
		this.Open();
		sda = new SqlDataAdapter(strSql, sqlconn);
		ds = new DataSet();
		sda.Fill(ds);
		this.Close();
		return ds;
		#endregion
	}

	/// <summary>
	/// 添加DataSet表
	/// </summary>
	/// <param name="ds">DataSet对象</param>
	/// <param name="strSql">Sql语句</param>
	/// <param name="strTableName">表名</param>
	public void GetDs(DataSet ds,string strSql,string strTableName)
	{
		#region
		this.Open();
		sda = new SqlDataAdapter(strSql, sqlconn);
		sda.Fill(ds, strTableName);
		this.Close();
		#endregion
	}

	/// <summary>
	/// 获取DataTable对象
	/// </summary>
	/// <param name="strSql"></param>
	/// <returns></returns>
	public DataTable GetTable(string strSql)
	{ 
		return this.GetDs(strSql).Tables[0];
	}

	/// <summary>
	/// 获得SqlDataReader对象 使用完须关闭DataReader，关闭数据库连接
	/// </summary>
	/// <param name="strSql"></param>
	/// <returns></returns>
	public SqlDataReader GetSqlDataReader(string strSql)
	{
		#region
		this.Open();
		cmd = new SqlCommand(strSql, sqlconn);
		sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
		return sdr;
		#endregion
	}

	/// <summary>
	/// 执行Sql语句
	/// </summary>
	/// <param name="strSql"></param>
	public void RunSql(string strSql)
	{
		#region
		this.Open();
		cmd = new SqlCommand(strSql, sqlconn);
		cmd.ExecuteNonQuery();
		this.Close();
		#endregion
	}

	/// <summary>
	/// 执行SQL语句，并返回第一行第一列结果
	/// </summary>
	/// <param name="strSql"></param>
	/// <returns></returns>
	public string RunSqlReturn(string strSql)
	{
		#region
		string strReturn = "";
		this.Open();
		try
		{
			cmd = new SqlCommand(strSql, sqlconn);
			strReturn = cmd.ExecuteScalar().ToString();
		}
		catch{}
		this.Close();
		return strReturn;
		#endregion
	}
}
