Susana Esparza
Susana Esparza

Reputation: 5

How to make a mysql query from c# and save it in a variable?

I want my c # program to take the data from the mysql database and save that data to a variable type double. I was trying but I still can't do it.

`

MySqlDataReader read = null;
            
string selectCmd = "SELECT Saldo from cuentas where NoCuenta=" + cuenta + ";";
            
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            
MySqlCommand MyCommand2 = new MySqlCommand(selectCmd, MyConn2);
            
MyConn2.Open();
            
read = MyCommand2.ExecuteReader();
            
MessageBox.Show("read: " +read);
            
bool saldoI = read.Read();
            
double saldo = Convert.ToDouble(saldoI);
           
 MessageBox.Show("Aqui se muestra el saldo inicial " + read);
            
double saldoFinal = saldo - monto;

`

I know that as I am transforming it from a bool type variable it returns a 1, but I require that it return the data type double. Example: 300.2

Upvotes: 0

Views: 245

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26352

Why not:

if (read.Read())
    double saldo = Convert.ToDouble(reader[0]);

The read.Read() return value, returns true if there is indeed a returned row from your query and false if there isn't or you read them all.

To actually get the data you need to access the current row's column in the data reader.

Example in the link above:

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        connection.Open();

        SqlCommand command = new SqlCommand(queryString, connection);
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}", reader[0]));
        }
    }
}

Upvotes: 1

Related Questions