我一直在
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();
}
答案 0 :(得分:6)
您需要先打开连接。
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.
}
}
这种方式更容易让GC无法收集资源。
HTH
答案 1 :(得分:2)
设置连接字符串后,需要调用conn.Open()。
编辑:Woops,Markust用40秒击败我,xD
答案 2 :(得分:-1)
更改您的连接字符串,如下所示......
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= c:\\inetpub\\wwwroot\\cm485a2\\rreAccesscm485a2.mdb";
*note: '\\' instead of '\'