[英]C# bulk insert to sql, but table is empty
我想从数据表中插入批量数据,但是在数据库中执行该表之后,当我测试查询以查看是否写入数据时,该表仍然为空。
下面是我从数据表插入到SQL的代码:
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!");
}
这是我创建/填充数据表的方式(数据表是全局声明的):
public void importExcel(string path, string sheetName)
{
var excel = new LinqToExcel.ExcelQueryFactory(path);
excel.ReadOnly = true;
var companies = from a in excel.Worksheet(sheetName) select a;
var columnNames = excel.GetColumnNames(sheetName);
foreach (var columnName in columnNames)
{
dtExcelRecords.Columns.Add(columnName);
}
foreach (var row in companies)
{
DataRow dr = dtExcelRecords.NewRow();
foreach (var columnName in columnNames)
{
dr[columnName] = row[columnName];
}
dtExcelRecords.Rows.Add(dr);
}
dataGridView1.DataSource = dtExcelRecords;
}
根据我的问题和在评论区域中收到的答案,问题似乎与默默捕获在代码块中的异常有关:
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
我的建议是DB访问逻辑(分离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层
这是一个重要的关注点分离,您还可以具有良好的异常管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.