Reputation: 41
So i have a class Take
for connecting to mysql. In that class I have a method to call a query to take the last record from mysql table.
public void Balance()
{
string query = "SELECT balance FROM history ORDER BY id DESC LIMIT 1 ";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}
}
In the main form I'm calling that class and that method
take.Balance();
I know, that from code above, i don't get any value but NULL
, so i am asking how i can take value from that query and put it in the TextBox
in the main form?
Upvotes: 0
Views: 180
Reputation: 186793
Let's have look:
// You probably want to return value: decimal, not void
public decimal Balance() {
// Make sql readable
string query =
@"SELECT balance
FROM history
ORDER BY id DESC
LIMIT 1 ";
// do not cache connection, but create a new one instead
using (MySqlConnection conn = new MySqlConnection(connectionStringHere)) {
conn.Open();
// wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(query, conn)) {
// you want to return values: ExecuteReader (or ExecuteScalar)
// instead of ExecuteNonQuery
using (var reader = cmd.ExecuteReader()) {
if (reader.Read())
return Convert.ToDecimal(reader.GetValue(0));
else
return 0m; // cursor is empty, let's return 0
}
}
}
}
Upvotes: 2
Reputation: 997
Personally, I think you should improve your basic knowledge of programming. There are two big problems in your example code:
For example:
public string Balance()
{
string query = "SELECT balance FROM history ORDER BY id DESC LIMIT 1 ";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
return cmd.ExecuteScalar();
}
}
Upvotes: 4
Reputation: 17605
There are two things to consider. First, the query
"SELECT balance FROM history ORDER BY id DESC LIMIT 1"
is a query in the sense that some useful data from the database should be returned, it should not be executed with a the method ExecuteNonQuery
, which is intended to return the number of rows affected by a non-query statement. Second, the return type of Balance
would have to be changed to some other type than void
, say int
or something similar, which would have to be returned to the caller.
Upvotes: 0