sqlHelper
![](/Images/OutliningIndicators/ContractedBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
/// <summary>
///MySqlHelper 的摘要说明
/// </summary>
public class MySqlHelper
{
protected static SqlConnection conn = new SqlConnection();
protected static SqlCommand comm = new SqlCommand();
public MySqlHelper()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 打开数据库连接
/// </summary>
private static void OpenConnection()
{
if (conn.State == ConnectionState.Closed)
{
conn.ConnectionString = "server=.;database=pubs;user=sa;pwd=database";
comm.Connection = conn;
try
{
conn.Open();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
/// <summary>
/// 关闭数据库连接
/// </summary>
private static void CloseConnection()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
comm.Dispose();
}
}
/// <summary>
/// 执行数据库语句
/// </summary>
/// <param name="sqlStr">数据库语句</param>
public static void ExcuteSql(string sqlStr)
{
try
{
OpenConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlStr;
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
CloseConnection();
}
}
/// <summary>
/// 返回指定sql语句的OleDbDataReader对象,使用时请注意关闭这个对象
/// </summary>
/// <param name="sqlStr">数据库语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader DataReader(string sqlStr)
{
SqlDataReader dr = null;
try
{
OpenConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlStr;
dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
dr.Close();
CloseConnection();
}
return dr;
}
/// <summary>
/// 返回指定sql语句的dataset
/// </summary>
/// <param name="sqlStr">数据库语句</param>
/// <returns>DataSet</returns>
public static DataSet DataSet(string sqlStr)
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
try
{
OpenConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlStr;
da.SelectCommand = comm;
da.Fill(ds);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
CloseConnection();
}
return ds;
}
/// <summary>
/// 返回指定sql语句的datatable
/// </summary>
/// <param name="sqlStr"></param>
/// <returns></returns>
public static DataTable DataTable(string sqlStr)
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
try
{
OpenConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlStr;
da.SelectCommand = comm;
da.Fill(dt);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
CloseConnection();
}
return dt;
}
}