Zobtzler
Zobtzler

Reputation: 33

C# MySQLDataReader returns same string for all rows

I'm trying to extract values from a table and the MySQLDataReader doesn't seem to want to cooperate with me.

conn = new MySqlConnection(Credentials);
conn.Open();
MySqlCommand cmd = new MySqlCommand(), cmd2 = new MySqlCommand();
cmd.Connection = conn;
cmd2.Connection = conn;
cmd.CommandText = "SELECT * FROM test";
cmd2.CommandText = "INSERT INTO test (test) VALUES (1),(2),(3),(4),(5),(6),(8);";
cmd2.ExecuteNonQuery();

MySqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
    Console.WriteLine(reader.ToString());
}
conn.Close();

The INSERT works as it should, as the table has been filled with the numbers 1-8 after checking the table, but this:

while (reader.Read())
{
    Console.WriteLine(reader.ToString());
}

returns this in the console

MySql.Data.MySqlClient.MySqlDataReader
MySql.Data.MySqlClient.MySqlDataReader
MySql.Data.MySqlClient.MySqlDataReader
MySql.Data.MySqlClient.MySqlDataReader
MySql.Data.MySqlClient.MySqlDataReader
MySql.Data.MySqlClient.MySqlDataReader
MySql.Data.MySqlClient.MySqlDataReader
MySql.Data.MySqlClient.MySqlDataReader

Upvotes: 2

Views: 1307

Answers (1)

haldo
haldo

Reputation: 16711

You need to access the columns of the SqlDataReader. You can read Retrieve data using a DataReader. The current code just calls ToString() on the reader, which just returns it's type.

You can extract data by:

reader.GetString(0)     // get a string in the first column
reader.GetInt32(1)      // get an integer in the second column
reader.GetValue(2)      // get an object in the third column
reader.GetDateTime(3)   // get a datetime   
reader.GetDouble(4)     // get a double

// or by index/indexing
reader["ColumnName"].ToString()  // get value by column name
reader[0].ToString()             // get value by index

So your code would become:

while (reader.Read())
{
    // get the value from the first column
    Console.WriteLine(reader.GetInt32(0));    
}

Upvotes: 5

Related Questions