错误42601语法错误在或接近

本文关键字:错误 接近 语法 42601 | 更新日期: 2023-09-27 18:13:36

我正在使用一个c#应用程序来加载一个带有适当数据的postgresql表。下面是代码:

NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;UserId=postgres;Password=***** ;Database=postgres;");
NpgsqlCommand command = new NpgsqlCommand();
command.Connection = conn;
conn.Open();
try {
  command.CommandText = "insert into projets (ID, Title, Path, Description, DateCreated) values('" + pro.ID + "','" + pro.Title + "','" + pro.Path + "', '' ,'" + pro.DateCreated + "')";
  command.ExecuteNonQuery();
} catch {
  throw;
}
conn.Close();

然而,当执行代码时,我一直得到相同的错误:

error 42601 syntax error at or near...

我不知道如何转义撇号。

错误42601语法错误在或接近

尝试使用参数化查询编写命令

command.CommandText = "insert into projets (ID, Title, Path, Description, DateCreated) " + 
                     "values(@id, @title, @path, '', @dt);";
command.Parameters.AddWithValue("@id", pro.ID);
command.Parameters.AddWithValue("@title", pro.Title);
command.Parameters.AddWithValue("@path", pro.PAth)
command.Parameters.AddWithValue("@dt", pro.DateCreated);
command.ExecuteNonQuery();

通过这种方式,如果您的字符串值之一包含一个单引号,您可以将正确解析您的值的工作留在框架代码中,并且您可以避免Sql注入问题