user2311028
user2311028

Reputation: 1711

error 42601 syntax error at or near

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

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.

Upvotes: 5

Views: 25757

Answers (1)

Steve
Steve

Reputation: 216353

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

Upvotes: 3

Related Questions