SqlBulkCopy - db2table中的空数据表
本文关键字:数据表 db2table SqlBulkCopy | 更新日期: 2023-09-27 17:54:55
现在我终于可以将csv的行(多少)写入表中了。它确实添加了csv的7行,但没有数据。它唯一设置的是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;
}
}
我不确定你的sbc.ColumnMappings。我认为,如果您的数据表没有反映db2表的结构,则只需要它。在我的代码中,我将数据表处理为具有与DB2表相同的列数和顺序。我不使用ColumnMappings。
第二:你的sbc.DestinationTableName。我在这里使用了一个字符串,其中包含来自DB2的确切模式和表名。DestinationTableName = "DB2-Schema。DB2-Tablename "
DB2运行在哪个版本上?从9.7版开始支持Bulkcopy