【问题标题】:error 42601 syntax error at or near错误 42601 在或附近出现语法错误
【发布时间】:2013-05-14 14:50:32
【问题描述】:

我正在使用 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...

我没有找到摆脱撇号的方法。

【问题讨论】:

  • 您确定要插入projets 而不是projects?
  • 在什么处或附近出现错误?
  • 除了@Brandon 所说的,我建议使用SqlParameters,这将完全解决转义字符串的问题,同时有助于防止 SQL 注入攻击。

标签: c# postgresql


【解决方案1】:

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

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 Injection 出现问题

【讨论】:

  • 非常感谢你 :)
猜你喜欢
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
  • 2021-02-28
  • 2017-03-16
  • 1970-01-01
相关资源
最近更新 更多