喜欢使用参数的npgsql语句

时间:2012-12-19 10:29:07

标签: c# asp.net npgsql

我有一个postgresql数据库,我想查询表“Locations”以检索与用户输入的名称相匹配的所有位置的名称。列名是“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

1 个答案:

答案 0 :(得分:12)

你应该使用

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 || '%'";
相关问题