我有一个 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
最佳答案
你应该使用
NpgsqlCommand cmd = new NpgsqlCommand("Select * from \"Locations\" where \"LocationName\" LIKE @loc_name", con);
cmd.Parameters.AddWithValue("@loc_name", "%" + Location_Name + "%");
您插入了太多引号:Postgre 将双引号之间的字符串解释为字段/表名。让参数完成转义字符串工作
P.S.:要在 Postgre 中连接字符串,您应该使用 ||
运算符,请参阅 here .所以你最后的查询应该是
string query = "Select \"LocationName\" from \"Locations\" where \"LocationName\" LIKE '%' || :loc_name || '%'";
关于c# - like 使用参数的 npgsql 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13950279/