10

我有一个 postgresql 数据库,我想查询表“位置”以检索与用户输入的名称匹配的所有位置的名称。列名是“LocationName”。我正在使用带有 C# 的 ASP.net。

NpgsqlConnection con = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString());

NpgsqlCommand cmd = new NpgsqlCommand("Select * from \"Locations\" where \"LocationName\" LIKE \"%@loc_name%\"", con);

cmd.Parameters.AddWithValue("@loc_name", Location_Name);

NpgsqlDataReader reader = cmd.ExecuteReader();

我得到这个例外:

Npgsql.NpgsqlException: ERROR: 42703: column "%((E'My place'))%" does not exist

我尝试在不使用 % 的情况下运行查询,但它不起作用。我也尝试过使用 + 和 & 如下所示,但这也不起作用:

string query = "Select \"LocationName\" from \"Locations\" where \"LocationName\" LIKE '%'+ :loc_name +'%'";

使用上面的行,我得到了这个异常:

Npgsql.NpgsqlException: ERROR: 42725: operator is not unique: unknown + unknown
4

1 回答 1

19

你应该使用

NpgsqlCommand cmd = new NpgsqlCommand("Select * from \"Locations\" where \"LocationName\" LIKE @loc_name", con);
cmd.Parameters.AddWithValue("@loc_name", "%" + Location_Name + "%");

您插入了太多引号:Postgre 将双引号之间的字符串解释为字段/表名。让参数完成转义字符串工作

PS:要在 Postgre 中连接字符串,您应该使用||运算符,请参见此处。所以你的最后一个查询应该是

string query = "Select \"LocationName\" from \"Locations\" where \"LocationName\" LIKE '%' || :loc_name || '%'";
于 2012-12-19T10:35:21.477 回答