gpt4 book ai didi

C# MySQL 参数 : ? 或 @

转载 作者:可可西里 更新时间:2023-11-01 07:22:35 24 4
gpt4 key购买 nike

我对 MySQL 参数有点困惑。

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

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();
}
}

第二个使用 ? 参数:

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();
}
}

These answers@? 工作正常。甚至 cmd.Parameters.AddWithValue("@name", name); 似乎也有效(注意名称中的 @)。

  1. 为什么它们都适用于 MySQL?

  2. 它们之间有区别吗?

  3. 哪一个是使用 MySQL 的正确方法?

感谢您提供的任何帮助。

最佳答案

来自documentation :

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 参数 : ? 或 @,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21206434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com