postgresql 错误 42601 语法错误位于或附近

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16546380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:54:57  来源:igfitidea点击:

error 42601 syntax error at or near

c#postgresql

提问by user2311028

I'm using a c# application to load a postgresql table with appropriate data. Here is the code:

我正在使用 ac# 应用程序加载具有适当数据的 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();

However, when executing the code, i keep getting the same error:

但是,在执行代码时,我不断收到相同的错误:

error 42601 syntax error at or near...

I didnt find how to escape the apostroph.

我没有找到如何逃避撇号。

采纳答案by Steve

Try to write your command using a parametrized query

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

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

In this way, if one of your strings values contain a single quote, you leave the job to correctly parse your values to the framework code and you avoid problems with Sql Injection

通过这种方式,如果您的字符串值之一包含单引号,您就可以将值正确解析到框架代码中,从而避免Sql 注入问题