【问题标题】:Insert all data of a datagridview to database C#将datagridview的所有数据插入数据库C#
【发布时间】:2015-05-06 17:19:58
【问题描述】:

我有一个数据网格视图,它是由各种操作和用户对数据的操作创建的。我想一次将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();    
        }
    }       
}

【问题讨论】:

  • 我没有看到问题。
  • 先生写此代码但无法在数据库表中插入值
  • 你得到的错误是什么?
  • executenonquery 的result 是什么?你能在你的 catch 块中写出异常消息吗?
  • 你的连接打开了吗?

标签: c# sql-server windows


【解决方案1】:

按原样,代码尝试执行参数化查询,但从未为参数分配值。即使这样做,也永远不会提取单元格值。

代码应如下所示:

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);
    }       
}

【讨论】:

    猜你喜欢
    • 2014-07-09
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多