Search code examples
c#mysqlwinformsexecutereader

C# write select from mysql to variable


I have a big problem with save variable from select in mysql.

I wrote the following code:

string connectionstring = @"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
MySqlDataReader reader = null;
string query_date = "SELECT computer_name from wp_users where user_login = @login";
MySqlCommand command2 = new MySqlCommand(query_date, cnn);
command2.Parameters.AddWithValue("@login", metroTextBox.Text);
reader = command2.ExecuteReader();
while (reader.Read())
{
   string ColumnName = (string)reader["computer_name"];
}
cnn.Close();

I tried a lot of commands like ExecuteReader , ExecuteNonQuery , ExecuteScalar. but none of them worked and I am getting the same error: enter image description here

Really don't know what is wrong here I searched a lot and didn't find a solution of any form. Please help.

EDIT 1

I just did how you wrote and i did this :

     string connectionstring = @"****;userid=*****;
        password=***;database=***";
        cnn = new MySqlConnection(connectionstring);
        cnn.Open();
        MySqlDataReader reader = null;
        string query_date = "SELECT computer_name from wp_users where user_login = @login";
        MySqlCommand command2 = new MySqlCommand(query_date, cnn);
        command2.Parameters.AddWithValue("@login", metroTextBox.Text);
        DataTable table = new DataTable("ResultTable");
            MySqlDataAdapter adapter = new MySqlDataAdapter(command2);
            adapter.Fill(table);

            // This is the important line
            string result = table.Rows[0].ToString();

            cnn.Close();

Its the same error as earlier but another place. What's going on here... just don't know. Additional information mean in english : The key is not present in the dictionary enter image description here

EDIT 2

The funniest is when i just try to update with code :

 string connectionstring = @"****;userid=*****;
    password=***;database=***";
    cnn = new MySqlConnection(connectionstring);
    cnn.Open();
    MySqlDataReader reader = null;
    string upd = "UPDATE w_users Set computer_name = CURRENT_DATE where user_login =  @login";
    MySqlCommand command2 = new MySqlCommand(upd, cnn);
    command2.Parameters.AddWithValue("@login", metroTextBox.Text);
    DataTable table = new DataTable("ResultTable");
    SqlDataAdapter adapter = new MySqlDataAdapter(command2);
    adapter.Fill(table);
    cnn.Close();

And this works fine without any errors just update my table... What's the point of it

EDIT 3

I jutr try used to ExecuteScalar() and still i have the same error : enter image description here


Solution

  • The solution is simple:

    Updating mysql.data.dll to the newest version fixed it (https://dev.mysql.com/downloads/connector/net/6.9.html).