开发者

Cant connect to remote MS Access database

开发者 https://www.devze.com 2023-02-17 06:25 出处:网络
I keep getting a InvalidOperationException: ExecuteReader requires an open and available Connection. The connection\'s current state is closed.]

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


You need to call conn.Open() after you set your connection string.

Edit: Woops, Markust beat me to it by 40 seconds, xD


change your connection string as follows...

conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
            @"Data source= c:\\inetpub\\wwwroot\\cm485a2\\rreAccesscm485a2.mdb";

*note: '\\' instead of '\'
0

精彩评论

暂无评论...
验证码 换一张
取 消