从asp.net执行MySql查询

时间:2011-02-22 16:27:38

标签: asp.net mysql

为什么这个命令不能正确执行:

    using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '@1', url = '@2' WHERE company = '@3'; ", myConn))
    {
        myCommand.Parameters.AddWithValue("@1", email);
        myCommand.Parameters.AddWithValue("@2", url);
        myCommand.Parameters.AddWithValue("@3", company);
        myConn.Open();
        myCommand.ExecuteNonQuery();
    }

但是当我用实际值替换@ 3时,它可以工作:

using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '@1', url = '@2' WHERE company = 'MyCompany'; ", myConn))
{
    myCommand.Parameters.AddWithValue("@1", email);
    myCommand.Parameters.AddWithValue("@2", url);

    myConn.Open();
    myCommand.ExecuteNonQuery();
}

公司变量传入的值与第二个示例中硬编码的值相同。我已经逐步使用调试器来确保公司变量被添加为参数,并且它是我期望的值。即。没有空格和trim()

知道我做错了吗?

更新

这也有效,但后来我不得不担心Sql Injection ......

    string myQuery = string.Format("Update jobs SET poster_email = '{0}', url = '{1}' WHERE company = '{2}'; ", email, url, company);

    using (MySqlCommand myCommand = new MySqlCommand(myQuery, myConn))
    {
        myConn.Open();
        myCommand.ExecuteNonQuery();
    }

1 个答案:

答案 0 :(得分:1)

我相信你想要使用“?”的MySQL命令而不是“@”:

using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '?1', url = '?2' WHERE company = '?3'; ", myConn))
{
    myCommand.Parameters.AddWithValue("?1", email);
    myCommand.Parameters.AddWithValue("?2", url);
    myCommand.Parameters.AddWithValue("?3", company);
    myConn.Open();
    myCommand.ExecuteNonQuery();
}

http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html#connector-net-examples-mysqlcommand-parameters