2013-03-10 268 views
0

我正在使用下面的代碼來訪問MS Access數據庫。但是我收到了錯誤消息填充:SelectCommand.Connection屬性尚未初始化。如何解決此問題。填充:SelectCommand.Connection屬性尚未初始化

common.cs 
========= 
public static bool DBConnectionStatus() 
     { 
      try 
      { 
       string conString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_admin.mdb; Jet OLEDB:Database Password=admin"; 
       using (OleDbConnection conn = new OleDbConnection(conString)) 
       { 
        conn.Open(); 
        return (conn.State == ConnectionState.Open); 
       } 
      } 
      catch (OleDbException) 
      { 
       return false; 
      } 


protected void btn_general_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       bool state = common.DBConnectionStatus(); 
       if (state == true) 
       { 
        cmd = new OleDbCommand("select * from tbl_admin"); 
        da = new OleDbDataAdapter(cmd); 
        DataSet ds = new DataSet(); 

        da.Fill(ds); // Error Here 
        if (ds.Tables[0].Rows.Count > 0) 
        { 

        } 

       } 
      } 
      catch (Exception e1) 
      { 
      } 
     } 
+3

的'using'將部署/關閉連接,因此該方法'DBConnectionStatus'是毫無意義的。 – 2013-03-10 12:03:33

+0

還有一件事是你必須分配連接到命令對象。 – 2013-03-10 12:11:04

回答

0

我也建議你修改你的代碼是這樣的:

private DataTable YourData() 
{ 
    string conString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_admin.mdb; Jet OLEDB:Database Password=admin"; 
    DataSet ds = new DataSet(); 
    using (SqlConnection conn = new SqlConnection(conString)) 
    { 
     try 
     { 
      conn.Open(); 
      SqlCommand command = new SqlCommand("select * from tbl_admin", conn); 
      command.CommandType = CommandType.Text; 

      SqlDataAdapter adapter = new SqlDataAdapter(command); 
      adapter.Fill(ds); 

      if (ds.Tables[0].Rows.Count > 0) 
      { 
       // do somethign here 
      } 
     } 
     catch (Exception) 
     { 
      /*Handle error*/ 
     } 
    } 
    return ds.Tables[0]; 
} 

然後:

protected void btn_general_Click(object sender, EventArgs e) 
{   
    this.YourData(); // you will get the Data here. you can then use it the way you want it   
} 
0

要初始化Command哪個喲u使用構建DataAdapter,但都沒有設置必要的Connection屬性:

cmd = new OleDbCommand("select * from tbl_admin"); // <-- no connectuion assigned 
da = new OleDbDataAdapter(cmd); // <-- no connectuion assigned 

所以你的例外是不言自明。

最後一點:usingdispose/closeconnection,因此該方法DBConnectionStatus是沒有意義的。所以,不要使用它,而是使用在using擺在首位:

try 
{ 
    using(var con = new OleDbConnection(connectionString)) 
    using(var da = new OleDbDataAdapter("elect * from tbl_admin", con)) 
    { 
     var table = new DataTable(); 
     da.Fill(table); // note that you don't need to open the connection with DataAdapter.Fill 
     if (table.Rows.Count > 0) 
     { 
      // ... 
     } 
    } 
} 
catch (Exception e1) 
{ 
    // don't catch an exception if you don't handle it in a useful way(at least loggging) 
    throw; 
} 
相關問題