在命令执行过程中遇到致命错误
本文关键字:遇到 致命错误 过程中 执行 命令 | 更新日期: 2023-09-27 18:18:51
我在c#中MySQL有一个问题。我想在MySQL数据库中搜索4个关键字,当我发现一个条目时,我的WPF程序将其显示在列表视图中,但我总是得到一个:
命令执行时遇到的致命错误
这里是我的代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
string strName = name.Text;
string strVorname = vorname.Text;
string strPLZ = plz.Text;
string strOrt = ort.Text;
try
{
MySqlConnection con = new MySqlConnection(@"Server=xx.xxx.xxx.xx;Uid=user;Pwd=pw;Database=db;");
con.Open();
MySqlCommand cmd = new MySqlCommand("SELECT Name, Vorname, Plz, FROM TBCustomer WHERE Name LIKE @strName AND Vorname LIKE @strVorname AND Plz LIKE @strPLZ", con);
cmd.Parameters.AddWithValue( "@Name", String.Format( "%{0}%", strName));
cmd.Parameters.AddWithValue( "@Vorname", String.Format( "%{0}%", strVorname));
cmd.Parameters.AddWithValue("@Plz", String.Format("%{0}%", strPLZ));
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())//Lese alle Datensätze aus
{
var getName = reader.GetString(reader.GetOrdinal("Name")); // 'String aus der Spalte "Name" auslesen
MessageBox.Show(getName);
}
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
使用
MySqlCommand cmd = new MySqlCommand("SELECT Name, Vorname, Plz FROM TBCustomer WHERE Name LIKE @strName AND Vorname LIKE @strVorname AND Plz LIKE @strPlz", con);
cmd.Parameters.AddWithValue( "@strName", String.Format( "%{0}%", strName));
cmd.Parameters.AddWithValue( "@strVorname", String.Format( "%{0}%", strVorname));
cmd.Parameters.AddWithValue("@strPlz", String.Format("%{0}%", strPLZ));
注意:没有被'
包围的参数被视为参数是正确的。
从查询中删除了一个,
(在Plz之后)!
检查参数名称:您可以这样更改代码段:
MySqlCommand cmd = new MySqlCommand("SELECT Name, Vorname, Plz, FROM TBCustomer WHERE Name LIKE '@Name' AND Vorname LIKE '@Vorname' AND Plz LIKE '@Plz' ", con);
cmd.Parameters.AddWithValue( "@Name", String.Format( "%{0}%", strName));
cmd.Parameters.AddWithValue( "@Vorname", String.Format( "%{0}%", strVorname));
cmd.Parameters.AddWithValue("@Plz", String.Format("%{0}%", strPLZ));