0

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

1 Answer 1

1

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]));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.