我想从我的数据表中插入批量数据,但是在我的数据库中执行该表后,当我测试查询以查看数据是否已写入时,它仍然是空的。
下面是我从数据表插入sql的代码:
try (DirectoryStream<Path> paths = Files.newDirectoryStream(pathToDir, regex)){
paths.forEach(path -> path.toFile().delete());
} catch (IOException e) {
// handle io exception
}
以下是我创建/填充数据表的方法(数据表是全局声明的):
private void btnToSql_Click(object sender, EventArgs e)
{
try
{
//First create a connection string to destination database
string connectionString;
connectionString = @"MY DATA STRING - I REPLACED IT JUST TO POST HERE";
//Open a connection with destination database;
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
//Open bulkcopy connection.
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(connection))
{
//Set destination table name
//to table previously created.
bulkcopy.DestinationTableName = "dbo.Table_1";
try
{
bulkcopy.WriteToServer(dtExcelRecords);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
connection.Close();
}
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
MessageBox.Show("Finished!");
}
答案 0 :(得分:0)
基于我的问题并在评论区域收到答案,问题似乎与在街区中无声捕获的异常有关:
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
我的建议是将数据库访问逻辑(DAL
)与UI
分开,方法是将此逻辑放在另一个类中(通常将它放在另一个程序集中)并具有如下模式:
数据层
try
{
// DB logic fetch
}
catch (Exception exc)
{
// log somewhere - NLog is one way to easily log to anything you want - console, DB, file - and also store important information such as timestamp, user, stack trace etc.
// put error in some output variable or property
}
UI图层
这是一个重要的关注点分离,您还可以进行良好的异常管理。