OleDbException未被用户代码处理 - 未指定错误

时间:2013-09-15 10:34:45

标签: c# ms-access ado.net

当我的程序运行时,以下错误会不断弹出。 相当新的,所以我不知道如何抓住这个...... 做了快速搜索,但似乎没有任何帮助。

以下是我的代码的一部分:

protected DBBase(string tableName, string primary_key)
{
    string s = Application.StartupPath + "\\alliancedb.accdb";
    conn = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}", s));
    if (conn.State == ConnectionState.Closed)
    {
        conn.Open();
        dataset = new DataSet();
        //query statement
        string sqlStatement = String.Format("Select * from {0} order by {1} ASC", tableName, primary_key);
        //run sql
        DBadpt = new OleDbDataAdapter(sqlStatement, conn);
        oOrderDetailsCmdBuilder = new OleDbCommandBuilder(DBadpt);
        DBadpt.Fill(dataset);
        dbTab = dataset.Tables[0];
        dbTab.TableName = this.tableName = tableName;

        rows = dbTab.Rows;
    }
    else if (conn.State == ConnectionState.Open)
    {
        conn.Close();
        conn.Open();
        dataset = new DataSet();
        //query statement
        string sqlStatement = String.Format("Select * from {0} order by {1} ASC", tableName, primary_key);
        //run sql
        DBadpt = new OleDbDataAdapter(sqlStatement, conn);
        oOrderDetailsCmdBuilder = new OleDbCommandBuilder(DBadpt);
        DBadpt.Fill(dataset);
        dbTab = dataset.Tables[0];
        dbTab.TableName = this.tableName = tableName;

        rows = dbTab.Rows;
    }
}

1 个答案:

答案 0 :(得分:1)

不要打开你的连接。始终打开它们,获取数据,然后立即关闭它们。 using块通常是为您关闭对象的最干净的方法。

此外,如果您的任何表格或字段是关键字或其中有空格,则必须将它们放在[方括号]中:

using (OleDbConnection conn = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}", s))) {
  conn.Open();
  string sqlStatement = String.Format("Select * from [{0}] order by [{1}] ASC", tableName, primary_key);
  // etc..
}