如何使用 sql Bulkcopy 在 table 中插入 datagridview 行

how to use sql Bulkcopy to insert datagridview rows in table

我想将 datagridview 行插入 sql 服务器 tables ... 现在使用此代码在 table 中插入来自 DataGridView 的行值:

private DataTable GetDataTableFromDGV(DataGridView dgv)
        {
            var dt = new DataTable();
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                if (column.Visible)
                {
                    dt.Columns.Add();
                }
            }
            object[] cellValues = new object[dgv.Columns.Count];
            foreach (DataGridViewRow row in dgv.Rows)
            {
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    cellValues[i] = row.Cells[i].Value;
                }
                dt.Rows.Add(cellValues);
            }
            return dt;
        }

        private void InsertDTtoDB(string ConnectionString, string TableName, DataGridView DGV)
        {
            DataTable dt = new DataTable();
            dt = GetDataTableFromDGV(DGV);
            using (SqlConnection cn = new SqlConnection(ConnectionString))
            {
                cn.Open();
                using (SqlBulkCopy copy = new SqlBulkCopy(cn))
                {                        
                    copy.ColumnMappings.Add(0, 1);
                    copy.ColumnMappings.Add(1, 2);
                    copy.ColumnMappings.Add(2, 3);
                    copy.ColumnMappings.Add(3, 4);
                    copy.ColumnMappings.Add(4, 5);
                    copy.DestinationTableName = TableName;
                    copy.WriteToServer(dt);
                }
            }
        }

但是插入数据时遇到问题: 来自 datatgridview 的空行(启用添加行)存储在最后 tables 行中! 请注意图片帮助:

首先,一些可能有助于您更好地理解用 C# 编写代码的一般观察:

// this line is declaring a new variable named 'dt' 
// and assigning it an instance of a new DataTable
DataTable dt = new DataTable();
// this line is immediately overwriting the new DataTable 
// assigned to 'dt' with the DataTable returned from 'GetDataTableFromDGV'
dt = GetDataTableFromDGV(DGV);

上面应该写成声明变量然后赋值:

DataTable dt = GetDataTableFromDGV(DBV);

来自 GetDataTableFromDGV 的以下内容将仅在列可见时向 DataTable 添加列:

foreach (DataGridViewColumn column in dgv.Columns)
{
    if (column.Visible)
    {
        dt.Columns.Add();
    }
} 

然后在 InsertDTtoDB 中使用上面的 DataTable 结果,这显然需要在预定义的序号位置设置一定数量的列:

copy.ColumnMappings.Add(0, 1);
// etc...

上面在 GetDataTableFromDGV 中创建的 DataTable 之间创建了一个非常脆弱的关系,它要求 Column 可见,然后在 InsertDTtoDB 中使用。

与其在 DataTable 和 SqlBulkCopy.ColumnMappings 之间使用脆弱的序号关系,不如使用字段名称创建 DataTable,然后映射到 SqlBulkCopy。 `GetDataTableFromDGV'中的foreach,则变为:

// assumes the columns in the DataGridView are named as follows:
var columns = new[] {"Id", "Invoice_Id", "Software_Id", "Price", "Quantity", "Sum" }
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
    // note: this is case-sensitive
    if (columns.Contains(column.Name))
    {
        dt.Columns.Add();
    }
}

然后 InsertDTtoDB 中的 ColumnMappings 变为:

copy.ColumnMappings.Add("Invoice_Id", "DestinationCol1");
copy.ColumnMappings.Add("Software_Id", "DestinationCol2");
// etc...

将行添加到 GetDataTableFromDGV 中的 DataTable 时,cellValues 变量在 foreach 循环外声明,但值在内部 for 循环中不断被覆盖。不是将对象数组添加到 DataTable,而是使用实际的列名称构建 DataRow 并将新的 DataRow 添加到 DataTable。

考虑到上述情况,GetDataTableFromDGV方法就变成了:

private DataTable GetDataTableFromDGV(DataGridView dgv)
{
    // use your actual columns names instead of Col1, Col2, etc...
    var columns = new[] {"Invoice_Id", "Software_Id", "Price", "Quantity", "Sum" }
    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns)
    {
        if (columns.Contains(column.Name))
        {
            dt.Columns.Add();
        }
    }

    foreach (DataGridViewRow row in dgv.Rows)
    {
        DataRow newRow = dt.NewRow();
        foreach (string columnName in columns)
        {
            newRow[columnName] = row.Cells[columnName].Value
        }

        dt.Rows.Add(newRow);
    }
    return dt;
}

然后 InsertDTtoDB 方法变为:

private void InsertDTtoDB(string ConnectionString, string TableName, DataGridView DGV)
{
    DataTable dt = GetDataTableFromDGV(DGV);
    using (SqlConnection cn = new SqlConnection(ConnectionString))
    {
        cn.Open();
        using (SqlBulkCopy copy = new SqlBulkCopy(cn))
        {   
            // update the "DestinationCol[x]" values to the destination column names
            copy.ColumnMappings.Add("Invoice_Id", "DestinationCol1");
            copy.ColumnMappings.Add("Software_Id", "DestinationCol2");
            copy.ColumnMappings.Add("Price", "DestinationCol3");
            copy.ColumnMappings.Add("Quantity", "DestinationCol4");
            copy.ColumnMappings.Add("Sum", "DestinationCol5");
            copy.DestinationTableName = TableName;
            copy.WriteToServer(dt);
        }
    }
}

为了回答您关于为什么将空行添加到数据库的问题,我怀疑这是因为 DataGridView 中存在空值。假设是这种情况,则将 DataGridView 中的空值排除在添加到 DataTable 之外。我会关闭其中一个关键列,例如 "Invoice_Id";然后 GetDataTableFromDGV 方法变为:

private DataTable GetDataTableFromDGV(DataGridView dgv)
{
    // assumes the columns in the DataGridView are named as follows:
    var columns = new[] {"Invoice_Id", "Software_Id", "Price", "Quantity", "Sum" }
    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns)
    {
        if (columns.Contains(column.Name))
        {
            dt.Columns.Add();
        }
    }

    foreach (DataGridViewRow row in dgv.Rows)
    {
        // check if the row has a null "Invoice_Id" and exclude
        if(row.Cells["Invoice_Id"] == null
        {
            continue;
        }

        DataRow newRow = dt.NewRow();
        foreach (string columnName in columns)
        {
            newRow[columnName] = row.Cells[columnName].Value
        }

        dt.Rows.Add(newRow);
    }
    return dt;
}