使用 DataReader 和 OLEDB Jet 数据提供程序读取 CSV 文件时,如何控制列数据类型? [英] When reading a CSV file using a DataReader and the OLEDB Jet data provider, how can I control column data types?

查看:26
本文介绍了使用 DataReader 和 OLEDB Jet 数据提供程序读取 CSV 文件时,如何控制列数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 C# 应用程序中,我使用 Microsoft Jet OLEDB 数据提供程序读取 CSV 文件.连接字符串如下所示:

In my C# application I am using the Microsoft Jet OLEDB data provider to read a CSV file. The connection string looks like this:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:Data;Extended Properties="text;HDR=Yes;FMT=Delimited

我使用该连接字符串打开一个 ADO.NET OleDbConnection,并使用以下命令从 CSV 文件中选择所有行:

I open an ADO.NET OleDbConnection using that connection string and select all the rows from the CSV file with the command:

select * from Data.csv

当我打开一个 OleDbDataReader 并检查它返回的列的数据类型时,我发现堆栈中的某些东西试图根据文件中的第一行数据猜测数据类型.例如,假设 CSV 文件包含:

When I open an OleDbDataReader and examine the data types of the columns it returns, I find that something in the stack has tried to guess at the data types based on the first row of data in the file. For example, suppose the CSV file contains:

House,Street,Town
123,Fake Street,Springfield
12a,Evergreen Terrace,Springfield

为 House 列调用 OleDbDataReader.GetDataTypeName 方法将显示该列的数据类型为DBTYPE_I4",因此从它读取的所有值都被解释为整数.我的问题是 House 应该是一个字符串 - 当我尝试从第二行读取 House 值时,OleDbDataReader 返回 null.

Calling the OleDbDataReader.GetDataTypeName method for the House column will reveal that the column has been given the data type "DBTYPE_I4", so all values read from it are interpreted as integers. My problem is that House should be a string - when I try to read the House value from the second row, the OleDbDataReader returns null.

如何告诉 Jet 数据库提供程序或 OleDbDataReader 将列解释为字符串而不是数字?

How can I tell either the Jet database provider or the OleDbDataReader to interpret a column as strings instead of numbers?

推荐答案

您可以创建一个架构文件,它会告诉 ADO.NET 如何解释 CSV - 实际上是给它一个结构.

There's a schema file you can create that would tell ADO.NET how to interpret the CSV - in effect giving it a structure.

试试这个:http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx

或者最新的MS 文档

这篇关于使用 DataReader 和 OLEDB Jet 数据提供程序读取 CSV 文件时,如何控制列数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆