2011-07-08 37 views
0

我试图读取使用的DataReader OleDb的.dbf文件这样的读取DBF文件:使用的IDataReader在C#中

const string OleDbConnectionString = 
    @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydbase;Extended Properties=dBASE IV;"; 
    var connection = new OleDbConnection(OleDbConnectionString); 
    connection.Open(); 

    var command = new OleDbCommand("select * from my.dbf", connection); 

    reader = command.ExecuteReader(); 
    Console.WriteLine(reader.Read()); // true 
    Console.WriteLine(reader[0].ToString()); // exception 

唯一的例外是InvalidCastException型的,并说:无法情况下,从System.__ComObjectIRowset 。 当我试图用OleDbAdapter来填充表格时,一切正常。
如何使用IDataReader读取.dbf文件?

+1

什么是你的选择命令中的'my.dbf'?如果不是,那该不该是表名呢? – dpp

回答

0

好吧,请尝试使用的GetString:

const string OleDbConnectionString = 
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydbase;Extended Properties=dBASE IV;"; 
OleDbConnection connection = new OleDbConnection(OleDbConnectionString); 
connection.Open(); 

OleDbCommand command = new OleDbCommand("select * from my.dbf", connection); 

OleDbDataReader reader = command.ExecuteReader(); 
Console.WriteLine(reader.Read()); // true 
Console.WriteLine("{0}", reader.GetString(0)); // exception 
+0

选择命令不是问题。我使用具有相同连接字符串的DataAdapter获得了所有工作。我尝试了你的建议 - 结果是同样的例外。 – StuffHappens

+0

放置类型没有帮助。 – StuffHappens

+0

@StuffHappens我刚刚在自己的DBF上运行你的代码,它工作,你可以把reader.GetString(0));在try/catch中提供异常信息?它是一个无法转换为字符串的值吗? – Andreas

1

我想既然你有“C:\ mybase”您的路径可能是错在ConnectionString,然后添加“my.dbf”这些加起来为“C :\ mybasemy.dbf”。

我提供代码如何打开并阅读使用数据集而不是阅读器的dbf。

string oledbConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\spcs\;Extended Properties=dBASE IV;User ID=Admin;Password="; 

     OleDbConnection oledbConnection = new OleDbConnection(oledbConnectionString); 

     string oledbQuery = @"SELECT * FROM KUND"; 

     try 
     { 
      OleDbCommand oledbCommand = new OleDbCommand(oledbQuery, oledbConnection); 

      OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(oledbCommand); 

      DataSet oledbDataset = new DataSet(); 

      oledbAdapter.FillSchema(oledbDataset, SchemaType.Mapped); 

      oledbConnection.Open(); 

      oledbAdapter.Fill(oledbDataset); 

      foreach (DataRow row in oledbDataset.Tables[0].Rows) 
      { 
       System.Diagnostics.Trace.WriteLine(row[0].ToString()); 
      } 
     } 
     catch (Exception ex) 
     { 
      // Do something with ex 
     } 
+0

感谢您的回答。但我需要用datareader来做,而不是数据集。 – StuffHappens