问题描述:

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?

网友答案:

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   
      }
    }          
  }
} 
网友答案:

Personally, I think you should improve your basic knowledge of programming. There are two big problems in your example code:

  1. You want to get the value, but your function is void, not return anything even set the value to some variable
  2. ExecuteNonQuery is not your case.

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();
        }          
    }
网友答案:

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.

相关阅读:
Top