Reputation: 101
So I'm trying to get data from a MySQL database and display it in a messageBox but I don't know how to get the result of the query I made, here's my code:
String^ constring = L"datasource=localhost; port=3306; username=root; password="; /
MySqlConnection^ conDB = gcnew MySqlConnection(constring);
MySqlCommand^ Query = gcnew MySqlCommand("SELECT Bar FROM utilizadores.users WHERE username='"+user+ "' ", conDB );
MySqlDataReader^ reader;
conDB->Open();
try
{
reader = Query->ExecuteReader();
MessageBox::Show(/*Result of the Query here*/);
}
catch (Exception^ex)
{
MessageBox::Show(ex->Message);
}
What do I have to put inside the MessageBox to display the result of that query?
Thanks
Upvotes: 1
Views: 125
Reputation: 901
To read the data you would typically use code like this. This assumes that Bar is of type double. You can change the type of Bar accordingly.
The Position of the bar_value=reader->getDouble(1) indicates that the result is in the first column.
Accordingly if you retrieved two columns and wanted the value of the second column that was also of type double you could use second_column=reader->getDouble(2)
The solution will look similar to this.
String^ constring = L"datasource=localhost; port=3306; username=root; password="; /
MySqlConnection^ conDB = gcnew MySqlConnection(constring);
MySqlCommand^ Query = gcnew MySqlCommand("SELECT Bar FROM utilizadores.users WHERE username='"+user+ "' ", conDB );
MySqlDataReader^ reader;
onDB->Open();
double^ bar_value;
String^ messagebox_bar_values;
try
{
reader = Query->ExecuteReader();
while (reader->Read())
{
bar_value=reader->GetDouble(1);
messagebox_bar_values=messagebox_bar_values+bar_value.ToString + ",";
//Alternatively the line below should also work. If we are not concerned about the datatype and read the value directly as a string.
//Just comment out the two lines above
//messagebox_bar_values=messagebox_bar_values+reader["Bar"]->ToString;
}
MessageBox::Show(messagebox_bar_values);
}
catch (Exception^ex)
{
MessageBox::Show(ex->Message);
}
A messagebox probably isn't the best way to display this particularly if you have a lot of data, for testing of course it will suffice. A textbox might be a better choice.
Upvotes: 1
Reputation: 24012
This should work:
reader = Query->ExecuteReader();
String bar = "Bar not found for the user '" & user & "'"
if( reader.Read() ) ' hope the statement returns a single row, and hence `if`
bar = reader.GetString( 0 )
end if
reader.close()
MessageBox::Show( bar );
Upvotes: 1