创建然后使用查询中的参数 [英] Creating and then working with parameters in queries
问题描述
我正在编写一个小型 XAML/C#/MySQL 数据库,并希望创建一个接受参数的查询.但是,当我尝试创建它时,我设置的测试查询失败
I am writing a small XAML/C#/MySQL database and wanted to create a query that accepts parameters. However, the test query that I am setting up fails when I try to create it
var con = new MySqlConnection(ClsVariables.StrDb);
con.Open();
var command = new MySqlCommand("", con);
command =
new MySqlCommand("Create View r2_Add_Edit_View as SELECT era.contact_id, era.n_family FROM era WHERE era.contact_id = @ContactID", con) command.ExecuteNonQuery();
con.Close();
当我将 @ContactID 更改为特定数字时 - 它工作正常.
When I change the @ContactID to a specific number - it works fine.
之后我需要创建一个记录集,并将参数传递给它(但我可以在第二个问题中提出这个问题).
After that I will need to create a recordset, and pass the parameter to it (but I can ask that in a secondary question).
一如既往的感谢.
推荐答案
当我将 @ContactID 更改为特定数字时 - 它工作正常.
When I change the @ContactID to a specific number - it works fine.
好吧,您没有传递参数,因此只需将其添加到您的命令中即可:
Well, you don't pass the parameter, so just add it to your command:
public class MySqlConnector
{
private readonly string _connString;
public MySqlConnector(string connString)
{
_connString = connString;
}
private MySqlCommand _command;
const string Sql = "Create View r2_Add_Edit_View as SELECT era.contact_id, era.n_family FROM era WHERE era.contact_id = @ContactID";
public void CreateView(int contactId)
{
if(_command == null)
{
_command = new MySqlCommand();
_command.CommandText = Sql;
_command.Connection = _connString;
}
_command.Parameters.AddWithValue("@ContactID", contactId);
_command.ExecuteNonQuery();
_command.Close();
}
}
这篇关于创建然后使用查询中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!