当我运行以下代码时:
query = "select count(*) from table where name = '?name'";
MySqlConnection connection =
new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("?name", name);
Int32 number = command.ExecuteScalar();
number
始终为零,即使转换为int也是如此。
我尝试将其转换为int64,没有骰子。我试过了command.Prepare()
。我尝试过使用Convert.ToInt32()
和其他所有变体。我已经尝试了几乎所有在阳光下的事情,包括逐字引用this建议的内容,我没有骰子。试图将对象转换为整数,作为一个long,作为int32,这似乎都不起作用。这些结果始终为0或导致MySQL错误。
编辑:堆栈溢出不会在代码标记中正确格式化该代码,我道歉
答案 0 :(得分:5)
原因是因为参数用单引号括起来,因此使它成为一个字符串。删除它,它会工作,
query = "select count(*) from table where name = @name";
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("@name", name);
更好的代码,
using
进行适当的对象处理try-catch
块来正确处理异常代码段,
query = "select count(*) from table where name = @name";
string connString =ConfigurationManager.ConnectionStrings["mydb"].ToString();
using(MySqlConnection connection = new MySqlConnection(connString))
{
using(MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.Add("@name", name);
try
{
connection.Open();
// other codes
}
catch(MySqlException ex)
{
// do somthing with the exception
// don't hide it
}
}
}