C# 批量插入到 sql,但表为空

本文关键字:sql 插入 | 更新日期: 2023-09-27 18:33:40

我想从我的数据表中插入批量数据,但是在我的数据库中执行表后,当我测试查询以查看数据是否已写入时,它仍然是空的。

以下是我从数据表插入到 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;
    }

C# 批量插入到 sql,但表为空

根据我的问题和评论区收到的答案,问题似乎与块中静默捕获的异常有关:

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
}

用户界面层

  • 调用数据层
  • 如果出现问题,请为用户打印友好的答案
  • 在日志中查找实际错误

这是一个重要的关注点分离,您还可以进行良好的异常管理。