C# 错误42601语法错误位于或接近
我正在使用一个c#应用程序加载一个带有适当数据的postgresql表。代码如下:C# 错误42601语法错误位于或接近,c#,postgresql,C#,Postgresql,我正在使用一个c#应用程序加载一个带有适当数据的postgresql表。代码如下: NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;UserId=postgres;Password=***** ;Database=postgres;"); NpgsqlCommand command = new NpgsqlCommand(); command.Connection = conn; conn.Open
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...
我不知道如何避开撇号 尝试使用参数化查询编写命令
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();
这样,如果您的一个字符串值包含一个引号,您就可以离开工作,正确地将您的值解析到框架代码中,并避免出现问题您确定要插入
projets
而不是projects
?除了@Brandon所说的错误之外,我建议使用它来解决字符串转义的问题,同时有助于防止SQL注入攻击。非常感谢:)