Dalal
Dalal

Reputation: 1106

Why does PostgreSQL treat a value in my query as if it's a column name?

I'm using Npgsql with C# to communicate with my PostgreSQL database. All names used in my database are mixed case, so in the query I make sure I use double quotes around each name. Here is how I am sending the query:

// construct an insert query
string insertQuery = "insert into \"Update\" (\"Vehicle\",\"Property\",\"Value\") " + 
                     "values (" + vehicleNum.ToString() + ",\"" + propertyName + 
                     "\",\"" + propertyValue + "\")";

// execute the query
NpgsqlCommand insertCommand = new NpgsqlCommand(insertQuery, conn);
insertCommand.ExecuteScalar();

By inserting a breakpoint and checking, I verified that the string insertQuery looks this before it is sent:

insert into "Update" ("Vehicle","Property","Value") values (12345,"EngineSpeed","50")

When I send this query, PostgreSQL gives me an error, which is wrapped up in an Npgsql exception that states: ERROR: 42703: column "EngineSpeed" does not exist

From my query, it should be evident that EngineSpeed is not a column, it is the value of the Property column, so naturally a column with that name is unlikely to exist. So why does PostgreSQL treat my query this way, and how can I solve this issue? Has my query been constructed the wrong way?

Upvotes: 1

Views: 3679

Answers (2)

Jon Hanna
Jon Hanna

Reputation: 113382

No, from the query you show it's evident that EngineSpeed is a column because it's escaped as such.

You also weren't taking care to make sure the values passed were escaped, which can be a serious security issue.

You want insert into "Update" ("Vehicle","Property","Value") values (12345,'EngineSpeed','50')

Which you could safely provide with:

string insertQuery = "insert into \"Update\" (\"Vehicle\",\"Property\",\"Value\") " + 
                     "values (" + vehicleNum.ToString() + ",'" + propertyName.Replace("'", "''") + 
                     "','" + propertyValue.Replace("'", "''") + "')";

Though you are better off using parameters with NPGSQL, which will handle this for you, including all of those nasty edge cases our unit tests are full of :)

Upvotes: 2

Kenaniah
Kenaniah

Reputation: 5201

Use single quotes to quote strings. Double quotes are used to denote column names.

Upvotes: 8

Related Questions