[英]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. 我在C#中使用Npgsql与PostgreSQL数据库进行通信。 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: 通过插入一个断点并进行检查,我验证了字符串
insertQuery
在发送之前看起来像这样:
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
当我发送此查询时,PostgreSQL给我一个错误,该错误包含在一个Npgsql异常中,该异常指出:
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. 从我的查询中,很明显
EngineSpeed
不是一列,而是Property
列的值,因此自然不存在具有该名称的列。 So why does PostgreSQL treat my query this way, and how can I solve this issue? 那么PostgreSQL为什么要这样处理我的查询,又该如何解决这个问题呢? Has my query been constructed the wrong way?
我的查询构造错误吗?
Use single quotes to quote strings. 使用单引号将字符串引起来。 Double quotes are used to denote column names.
双引号用于表示列名。
No, from the query you show it's evident that EngineSpeed is a column because it's escaped as such. 不,从查询中您可以看到,显然EngineSpeed是一列,因为它是这样转义的。
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')
您要
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 :) 尽管您最好在NPGSQL中使用参数,它将为您处理此问题,包括我们的单元测试中充满了所有那些讨厌的极端情况:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.