简体   繁体   English

将datagridview的所有数据插入数据库C#

[英]Insert all data of a datagridview to database C#

I have a datagridview which is created by various action and user's manipulation of data. 我有一个datagridview,它由各种操作和用户对数据的操作创建。 I want to insert all the data of the gridview to the database at once, I know I could try a code similar to this: 我想立即将gridview的所有数据插入数据库,我知道我可以尝试类似这样的代码:

private void btnSaveProducts_Click(object sender, EventArgs e)
{
    SqlConnection connection = DBConnectivity.getConnection();
    if (connection != null)
    {
        try
        {
            for (int i = 0; i < dGvProducts.Rows.Count; i++)
            {
                string query = "INSERT INTO product (productName) " + "VALUES (@productName)";
                SqlCommand command = DBConnectivity.getCommandForQuery(query, connection);
                    int result = command.ExecuteNonQuery();
                    Console.WriteLine(result + "");
            }
            //  string query = "Insert into units(name,packing)values('" + txtNameUnit.Text + "' , '" + txtPackingUnit.Text + "')";
            //  SqlCommand command = DBConnectivity.getCommandForQuery(query, connection);
            //  int result = command.ExecuteNonQuery();
            //  Console.WriteLine(result + "");
        }
        catch (Exception ex)
        {
        }
        finally
        {
            connection.Close();    
        }
    }       
}

As is, the code tries to execute a parameterized query but never assigns a value to the parameter. 原样,代码尝试执行参数化查询,但从不为参数赋值。 Even if you do, you never extract the cell values. 即使你这样做,也永远不会提取单元格值。

The code should look like this: 代码应该如下所示:

var query = "INSERT INTO product (productName) VALUES (@productName)";

using var(connection = DBConnectivity.getConnection())
using(var command = new SqlCommand(query, connection))
{
    var productParam=command.Parameters.Add("@productName",SqlDbType.NVarChar,50);

    connection.Open();
    for (int i = 0; i < dGvProducts.Rows.Count; i++)
    {                    
        var productName=dGvProducts.Rows[i].Cells[somecolumn].Value;
        productParam.Value=productName;
        int result = command.ExecuteNonQuery();
        Console.WriteLine(result);
    }       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM