Default.aspx页面
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataGrid1.DataSource =DbSqlOperation.GetDataReader("Select * from Menu");
DataGrid1.DataBind();
DbSqlOperation.CloseCon();
}
}
----------------------------------------------------------------------
DbSqlOperation.cs页面
public class DbSqlOperation
{
protected static OleDbConnection Con = Dbcon.CreateCon();
protected static OleDbCommand Cmd = new OleDbCommand();
protected static OleDbDataReader dr = null;
public DbSqlOperation()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 打开数据库连接
/// </summary>
private static void OpenCon()
{
if (Con.State == ConnectionState.Closed)
{
try
{
Con.Open();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
/// <summary>
/// 关闭连接,并且释放连接和命令对象
/// </summary>
public static void CloseCon()
{
if (Con.State == ConnectionState.Open)
{
Con.Close();
Con.Dispose();
Cmd.Dispose();
}
}
/// <summary>
/// 释放OledbDataReader对象
/// </summary>
public static void CloseDataReader()
{
dr.Close();
dr.Dispose();
}
/// <summary>
/// 执行SQL语句,返回OleDbDataReader
/// </summary>
/// <param name="sql">string</param>
/// <returns>OleDbDataReader</returns>
public static OleDbDataReader GetDataReader(string sql)
{
Cmd.Connection = Con;
Cmd.CommandType = CommandType.Text;
Cmd.CommandText = sql;
try
{
OpenCon();
dr = Cmd.ExecuteReader();
return dr;
}
catch (Exception e)
{
CloseCon();
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行SQL语句,返回DataSet
/// </summary>
/// <param name="sql">string</param>
/// <returns>DataSet</returns>
public static DataSet GetDataSet(string sql)
{
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter();
Cmd.Connection = Con;
Cmd.CommandType = CommandType.Text;
Cmd.CommandText = sql;
try
{
OpenCon();
sda.SelectCommand = Cmd;
sda.Fill(ds);
return ds;
}
catch(Exception e)
{
throw new Exception(e.Message);
}
finally
{
CloseCon();
sda.Dispose();
}
}
----------------------------------------------------------------------
我要疯了。 老是调试..老是数据库连接的问题。第一次可以连.
刷新一下。就报错.我要疯了。哪个大侠解答一下。