C#MySQL参数:?或者 @ [英] C# MySQL Parameters : ? or @

查看:88
本文介绍了C#MySQL参数:?或者 @的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对MySQL参数感到困惑.

I'm kind of confused with the MySQL parameters.

我的代码的以下两个部分都可以正常工作.第一个使用@的参数:

Both of the following parts of my code work fine. The first one uses parameters with @ :

const string query = "UPDATE `items` SET `name` = @name, `price` = @price WHERE `id` = @id";
try
{
    using (MySqlCommand cmd = new MySqlCommand(query, Database.MyConnection))
    {
        cmd.Parameters.AddWithValue("name", name);
        cmd.Parameters.AddWithValue("price", price);
        cmd.Parameters.AddWithValue("id", id);
        cmd.ExecuteNonQuery();
    }
}

第二个将参数与?一起使用:

Second uses parameters with ? :

const string query = "UPDATE `items` SET `name` = ?name, `price` = ?price WHERE `id` = ?id";
try
{
    using (MySqlCommand cmd = new MySqlCommand(query, Database.MyConnection))
    {
        cmd.Parameters.AddWithValue("name", name);
        cmd.Parameters.AddWithValue("price", price);
        cmd.Parameters.AddWithValue("id", id);
        cmd.ExecuteNonQuery();
    }
}

这些答案都说@?工作正常. 甚至cmd.Parameters.AddWithValue("@name", name);似乎都可以工作(请注意名称中的@).

These answers say both @ or ? work fine. Even cmd.Parameters.AddWithValue("@name", name); seems to work (note the @ in the name).

  1. 为什么它们都可以在MySQL上正常工作?

  1. Why all of them work fine with MySQL ?

它们之间有区别吗?

哪种是与MySQL一起使用的正确方法?

Which one is the proper way to use with MySQL ?

感谢我的帮助.

推荐答案

来自

提供程序的早期版本使用'@'符号在SQL中标记参数.这与MySQL用户变量不兼容,因此提供程序现在使用?"符号以在SQL中定位参数.要支持较旧的代码,可以在连接字符串上设置"old语法=是".如果这样做,请注意,如果您未能定义要在SQL中使用的参数,则不会引发异常.

Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL.

这篇关于C#MySQL参数:?或者 @的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆