我需要在Microsoft SQL Server 2000中如何通過OLEDB在C#中導入CSV文件時,指定分隔符
執行復雜的進口由於在DTS做實在是太複雜了,我試圖做它帶有一點C#程序,但是當我需要導入一個CSV文件時,我遇到了問題:該文件使用分號作爲字段分隔符而不是逗號,而且我無法讓.NET的OLE DB提供程序識別它。
我已經在網上找到了像使用Extended Properties="Text; Format=Delimited"
或``Extended Properties =「Text; Format = Delimited(;)」in the connection string or using a
schema.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);
}
}
}
有關如何使用分號作爲字段分隔符來實現的任何想法,而不依賴於外部libriaries?
注:
- 的「不依賴於外部libriaries」位,是因爲我需要直接將文件導入數據庫,沒有圖書館,我發現能做到這一點(他們返回字符串),和我們的PHB即使是商業解決方案也不會降低一分錢。
- 我知道我可以通過DTS導入文件,但是我需要在導入之前和之後對工作流和文件更改執行復雜的分支,這會導致跳入和跳出DTS。
- 在DTS內部做所有事情對我來說都是不實際的,因爲我不擅長ActiveX和VBScript編碼。
在此先感謝安德烈。
編輯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);
}
}
}
您的代碼在SqlConnection字符串內部使用OleDbConnection字符串和OLE DB提供程序語法的SQL提供程序語法。請問這是問題嗎? – 2010-06-24 11:37:57
@Panagiotis Kanavos:剪切並粘貼錯誤,已更正。 – Albireo 2010-06-24 12:56:49