无法连接到远程MS Access数据库 [英] Cant connect to remote MS Access database
问题描述
我不断收到一个
出现InvalidOperationException:ExecuteReader需要一个开放和可用的连接。连接的当前状态为已关闭。]
这是因为我的连接被关闭。有什么不对我的连接字符串?为什么不打开它。
保护无效的Page_Load(对象发件人,EventArgs的发送)
{
//声明部分 // OleDbConnection的objDBConn;
OleDbCommand的objCmd;
OleDbDataReader objDR; //创建连接对象
System.Data.OleDb.OleDbConnection康恩=新
System.Data.OleDb.OleDbConnection(); //修改连接字符串,并包括任何
//其他所需的属性数据库。
conn.ConnectionString = @供应商= Microsoft.Jet.OLEDB.4.0; +
@数据来源= C:\\的Inetpub \\ wwwroot的\\ cm485a2 \\ rreAccesscm485a2.mdb //使用SQL创建OleDbCommand对象执行
objCmd =新的OleDbCommand(SELECT *+
客户+
ORDER BY CUST_ID,康恩); //创建一个DataReader并执行命令
objDR = objCmd.ExecuteReader(); //从DataReader的复制结果DataGrid对象
GridView1.DataSource = objDR;
GridView1.DataBind();
//关闭所有对象
conn.Close();
conn.Dispose(); }
您需要先打开连接。
的http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection.open.aspx
另外,我会使用使用
要避免资源泄漏,是这样的:
使用(VAR连接=新的OleDbConnection())
{
connection.Open();
使用(VAR命令=新的OleDbCommand(的connectionString))
{
//做我的东西。
}
}
这方面是比较容易的GC离开未收集资源。
心连心
I keep getting a
InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.]
It is because my connection is closed. What is wrong with my connection string? Why won't it open.
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();
}
You need to Open the connection first.
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection.open.aspx
also, I would use using
to be avoid resource leaks, something like this:
using (var connection = new OleDbConnection())
{
connection.Open();
using (var command = new OleDbCommand("connectionString"))
{
//Do my stuff.
}
}
This ways is easier to leave resources uncollected by the GC.
HTH
这篇关于无法连接到远程MS Access数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!