nicBit
nicBit

Reputation: 63

fatal error encountered during command execution mysql c#

I have a Problem during MySQL in C#. I want to search for 4 Keywords in my MySQL Database and when i found an entry my WPF Program display it in a listview but i get always an:

fatal error encountered during command execution

here my code:

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

Upvotes: 1

Views: 22120

Answers (2)

TJ-
TJ-

Reputation: 14363

Use this

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

Note : Params not surrounded by ' is correct for them to be treated as params.

Removed a , from the query (after Plz)! That was nuts.

Upvotes: 1

Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Check the parameters names : You can change your snippet like this :

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

Upvotes: 0

Related Questions