我需要在Microsoft SQL Server 2000中执行复杂的导入.
由于在DTS中执行它太复杂了,我正在尝试使用一个小的C#程序,但是当我需要导入CSV文件时我遇到了问题:这个文件使用分号作为字段分隔符而不是逗号和我无法让.NET的OLE DB提供程序识别它.
我已经在网上找到了各种"解决方案",比如使用Extended Properties="Text; Format=Delimited"或者``Extended Properties ="Text; Format = Delimited(;)" in the connection string or using aschema.ini`文件无济于事.
这是我正在使用的实际代码:
DataTable Table = new DataTable();
using (OleDbConnection Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text;HDR=Yes;Format=Delimited\""))
{
Connection.Open();
using (OleDbCommand Command = Connection.CreateCommand())
{
Command.CommandText = "select [Field 1], [Field 2] from [file.csv]";
using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command))
{
Adapter.Fill(Table);
}
}
}
using (SqlConnection Connection = new SqlConnection("Data Source=server; Initial Catalog=database; User Id=user; Password=password;"))
{
Connection.Open();
using (SqlCommand Command = Connection.CreateCommand())
{
Command.CommandText = "insert into [table] ([field_1], [field_2], ...) values (@field_1, @field_2, ...)";
Command.Parameters.Add("field_1", SqlDbType.Date, 0, "Field 1");
Command.Parameters.Add("field_2", SqlDbType.VarChar, 100, "Field 2");
...
using (SqlDataAdapter Adapter = new SqlDataAdapter())
{
Adapter.InsertCommand = Command;
Adapter.Update(Table);
}
}
}
Run Code Online (Sandbox Code Playgroud)
关于如何使用分号作为字段分隔符而不依赖外部libriaries的任何想法?
笔记:
提前谢谢,安德烈.
编辑1 - @andyb:方法的
测试程序代码schema.ini:
String ConnectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text\"", Environment.CurrentDirectory);
DataTable Table = new DataTable();
using (OleDbConnection Connection = new OleDbConnection(ConnectionString))
{
Connection.Open();
using (OleDbCommand Command = Connection.CreateCommand())
{
Command.CommandText = "select * from [file.csv]";
using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command))
{
Adapter.Fill(Table);
}
}
}
Run Code Online (Sandbox Code Playgroud)
and*_*dyb 13
Commenter是对的,你的提供者语法是错误的.
但是,这不是问题.遗憾的是,您无法在oledb连接字符串中指定自定义分隔符.而是在与包含以下内容的源文件相同的目录中创建schema.ini文件:
[file.csv]
Format=Delimited(;)
Run Code Online (Sandbox Code Playgroud)
笨拙,但确实有效.
| 归档时间: |
|
| 查看次数: |
35801 次 |
| 最近记录: |