Mik*_*ike 2 c# asp.net ms-access
我一直在接受
InvalidOperationException:ExecuteReader需要一个开放且可用的连接.连接的当前状态已关闭.]
这是因为我的连接已关闭.我的连接字符串有什么问题?为什么不打开它.
protected void Page_Load(object sender, EventArgs e)
{
// Declaration section
//OleDbConnection objDBConn;
OleDbCommand objCmd;
OleDbDataReader objDR;
//create connection object
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= c:\inetpub\wwwroot\cm485a2\rreAccesscm485a2.mdb";
// Create OleDbCommand object with SQL to execute
objCmd = new OleDbCommand("SELECT * " +
" FROM customers " +
" ORDER BY cust_id", conn);
// Create a DataReader and execute the command
objDR = objCmd.ExecuteReader();
// Copy results from DataReader to DataGrid object
GridView1.DataSource = objDR;
GridView1.DataBind();
//close all objects
conn.Close();
conn.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
您需要先打开连接.
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection.open.aspx
另外,我会using用来避免资源泄漏,如下所示:
using (var connection = new OleDbConnection())
{
connection.Open();
using (var command = new OleDbCommand("connectionString"))
{
//Do my stuff.
}
}
Run Code Online (Sandbox Code Playgroud)
这种方式更容易留下GC无法收集的资源.
HTH