Error from OdbcDataAdapter.Fill

2019-08-25 04:07发布

I sometimes get two different of error when executing OdbcDataAdapter.Fill(DataTable). Here is the code example:

string odbc = "select item, upcno from table";
OdbcCommand cmd = new OdbcCommand(odbc, fconn);
OdbcDataAdapter oda = new OdbcDataAdapter(cmd);
oda.Fill(dt);
  1. System.NullReferenceException: Object reference not set to an instance of an object.

  2. System.InvalidOperationException: No data exists for the row/column.

Does anyone have clue to resolve this problem?

1条回答
贪生不怕死
2楼-- · 2019-08-25 04:42

Not sure where you get connection object from your question but you can do as below. don't create class level connections, you can create it when you want and properly dispose it at the end.

public DataTable GetDataTableFromAdapter(string queryString)
{
    DataTable dt = new DataTable();
    using (OdbcConnection connection =
                new OdbcConnection(ConnectionString))
    {
        using (OdbcDataAdapter adapter =
                new OdbcDataAdapter(queryString, connection))
        {
            connection.Open();
            adapter.Fill(dt);
        }
    }
    return dt;
}

Call it as

DataTable dt = GetDataTableFromAdapter("select [item], [upcno] from [table]");
查看更多
登录 后发表回答