大家帮我看下为何这样老是获取不了值呢?
public Object ExecuteScalar(string cmdStr, params string[] pars)
{
using (MySqlConnection con = new MySqlConnection(conStr))
{
using (MySqlCommand com = new MySqlCommand(cmdStr, con))
{
for (int i = 0; i < pars.Length; i += 2)
{
com.Parameters.Add(pars[i], pars[i + 1]);
}
con.Open();
return com.ExecuteScalar();
}
}
}
调用:
string strSQL = "select sum(pwd)from test where pwd=@field1";
ExecuteScalar(strSQL, new string[] { "@field1", "9" }).ToString();
查询结果老是为空,但是数据库中有 pwd=9 的数据的。
是否是转义符的问题?
你试下:
string strSQL = @"select sum(pwd)from test where pwd=@field1";
//或string strSQL = "select sum(pwd)from test where pwd=\@field1";
ExecuteScalar(strSQL, new string[] { "@field1", "9" }).ToString();
com.Parameters.Add(pars[i], pars[i + 1]);
上面方法已经过时了吧,用下面这个。
cmd.Parameters.AddWithValue(pars[i], pars[i + 1]);
另外,指定一下com 的类型 cmd.CommandType = CommandType.Text;
Code
public Object ExecuteScalar(string cmdStr, params string[] pars)
string strSQL = "select sum(pwd)from test where pwd=@field1";
ExecuteScalar(strSQL, new string[] { "@field1", "9" }).ToString();
方法签名和调用的参数不符合吧?