【问题标题】:Inserting data from DatagridView error从 DatagridView 插入数据错误
【发布时间】:2017-04-07 04:03:06
【问题描述】:

我有

string insert_cmd_str;

using (conn_server)
{
    using (NpgsqlCommand insert_cmd = new NpgsqlCommand())
    {
        insert_cmd.Connection = conn_server;
        conn_server.Open();
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            insert_cmd_str = "insert into @table values (" +
                                 "'" + dataGridView1.Rows[i].Cells[0].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[1].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[2].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[3].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[4].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[5].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[6].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[7].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[8].FormattedValue + "', " +
                                 "'" + dataGridView1.Rows[i].Cells[9].FormattedValue + "')";
            insert_cmd.CommandText = insert_cmd_str;
            insert_cmd.Parameters.AddWithValue("@table", "table");


            MessageBox.Show(insert_cmd.CommandText + Environment.NewLine +
                            insert_cmd.Parameters["@db"].Value);

            insert_cmd.ExecuteNonQuery();
        }
        conn_server.Close();
    }
}

我得到一个错误:

错误:42601:“(”或附近的语法错误

我添加了MessageBox 以在命令文本执行之前检查它,这似乎很好。如果我将相同的文本发布到 PG admin 中,它会执行命令而不会出现错误。

命令文本为:

insert into @table values ('425', '10-31-2016 00:00:00', 'False', '', 'test', 'test', 'test', 'pas_kosmetologus', 'Skambutis', '237')

@table 的值为table。 我不知道错误是从哪里来的。我什至尝试从命令文本中删除两个括号,但仍然抛出相同的错误。

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • 你的桌子叫桌子?那是一个可能导致您出现问题的关键字。
  • 并非如此。我只是在这里更改它以简化它。需要向其中插入数据的表的实际名称取决于应用程序的用户。
  • 可能是插入语句首先需要列,例如insert into (column1, ...) values (value1, ...)
  • 现在是 vizitai_test。我认为这不会导致错误。
  • @Martynas 你检查了吗?

标签: c# sql winforms visual-studio npgsql


【解决方案1】:

PostgreSQL 不支持参数化表或列名 - 您必须将它们连接到您的字符串中(但要注意 SQL 注入),或者编写一个 plpgsql。示例见https://stackoverflow.com/a/13289939/640325

无论如何,连接数据网格中的值会使您对 SQL 注入敞开大门,请考虑在此处使用参数。

【讨论】:

  • 我已将表名从参数更改为字符串,并且可以正常工作。
猜你喜欢
  • 2018-01-25
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2014-02-18
  • 2013-03-01
  • 2014-01-06
相关资源
最近更新 更多