Parameters.AddWithValue不起作用



我有以下代码(查询缩写):

string q_sel = @"SELECT c.editedBy, c.*
                 FROM wf.chan c
                 WHERE date(editedTime) >= current_date - ? AND editedBy = '?') c2
                 ORDER BY editedTime";
if (myConnection.State != ConnectionState.Open)
    OpenDb();
myCommand = new OdbcCommand(q_sel, myConnection);
myCommand.Parameters.AddWithValue("@0", Request.QueryString["days"]);
myCommand.Parameters.AddWithValue("@1", Request.QueryString["user"]);
OdbcDataReader myReader = myCommand.ExecuteReader();

如果我手动用const值替换?,那么查询就可以工作,但用Parameters.AddWithValue就不行了,知道为什么吗?

AddWithValue从作为其第二个参数传递的值中假定(有时会出错)参数的数据类型。所以你的线路
 myCommand.Parameters.AddWithValue("@0", Request.QueryString["days"]);

为第一个参数传递一个字符串,而不是像您期望的那样传递一个数字。我将尝试在中更改该行

 myCommand.Parameters.AddWithValue("@0", Convert.ToInt32(Request.QueryString["days"]));

还可以考虑使用代码创建的特定参数,在该参数中可以设置DataType和Size

OdbcParameter p = new OdbcParameter("@0", OdbcType.Int)
p.Value = Convert.ToInt32(Request.QueryString["days"]))
myCommand.Parameters.Add(p);

或者更好的是像这样的一行

myCommand.Parameters.Add("@0", OdbcType.Int).Value = Convert.ToInt32(Request.QueryString["days"]);

最新更新