现在我终于把我的csv(有点)的行写到表中了。它确实添加了7行的csv,但没有数据。它唯一设置的是id,但无论如何都会自动增加。 csv中的数据无法到达表格中。
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader, string csvSelection)
{
string header= isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
List<string> headerList = getHeader(fileName);
string sql = @"SELECT " + "*" + " FROM [" + fileName + "]";
//string sql = @"SELECT * FROM [" + fileName + "];";
using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + headerList + ";FMT=Delimited(;)\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
foreach (var item in headerList)
{
dataTable.Columns.Add(item);
}
adapter.Fill(dataTable);
writeSchema(dataTable.Columns, pathOnly, fileName);
return dataTable;
}
}
public static Boolean BatchBulkCopy(DataTable dt, string destTable, List<string> columnMapping, IBM.Data.DB2.DB2Connection connection, int batchSize)
{
DataTable dtInsertRows = dt;
using (IBM.Data.DB2.DB2BulkCopy sbc = new IBM.Data.DB2.DB2BulkCopy(connection, IBM.Data.DB2.DB2BulkCopyOptions.TableLock))
{
sbc.DestinationTableName = "\"" + destTable + "\"";
foreach (var mapping in columnMapping)
{
var split = mapping.Split(new[] { ',' });
sbc.ColumnMappings.Add("\"" + split.First() + "\"", "\"" + split.Last() + "\"");
}
try{
sbc.WriteToServer(dtInsertRows);
sbc.Close();
}
catch(Exception e){
System.Console.WriteLine(e.ToString());
}
}
connection.Close();
return false;
}
private static void writeSchema(DataColumnCollection columns, string csvDir, string csvFileName)
{
FileStream fsOutput =
new FileStream(csvDir + "\\schema.ini",
FileMode.Create, FileAccess.Write);
StreamWriter srOutput = new StreamWriter(fsOutput);
srOutput.WriteLine("[" + csvFileName + "]");
int i = 1;
foreach (DataColumn item in columns)
{
srOutput.WriteLine("Col" + i + "=\"" + item.ToString() + "\" Text");
i++;
}
srOutput.Close();
fsOutput.Close();
}
private static List<string> getHeader(string fileName)
{
string fullpath = @ImportPath + "\\" + fileName;
List<string> header = new List<string>();
var reader = new StreamReader(File.OpenRead(fullpath));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
foreach (var spalte in values)
{
header.Add(spalte);
}
reader.Close();
return header;
}
return null;
}
}
答案 0 :(得分:0)
DB2正在运行什么版本?版本9.7支持Bulkcopy
答案 1 :(得分:0)
我不确定你的sbc.ColumnMappings。我认为如果您的数据表没有反映db2表的结构,则只需要它。在我的代码中,我处理数据表,使其具有与DB2表相同的列数和顺序。我不使用ColumnMappings。
第二名:你的sbc.DestinationTableName。我在这里使用一个带有DB2的确切模式和表名的字符串。 DestinationTableName =“DB2-Schema.DB2-Tablename”