简体   繁体   中英

C# dataReader not working properly

I am trying to take a single value from a database, but the cycle does not seem to start at all?

if (connection.State == ConnectionState.Open)
        {
            MySqlDataReader dataReader = cmd.ExecuteReader();
            while (dataReader.Read())
            {
                value = dataReader["amount"].ToString();
            }
            dataReader.Close();
            connection.Close();
        }

These are the commands:

 public string value; 
    public static string Konekcija = "Server=127.0.0.1; Database=CardIgrica; Uid=admin; Pwd=admin;";
    public string komanda = "SELECT amount FROM CardIgrica.creaures WHERE id = '1';";
    MySqlConnection connection = new MySqlConnection(Konekcija);
MySqlCommand cmd = new MySqlCommand(komanda, connection);
connection.Open();

try this for the select

public string value {get; set;}
string komanda ="SELECT amount FROM CardIgrica.creaures WHERE id = 1"; 

First open your sql connection then make object of MySqlCommand like below:

MySqlConnection connection = new MySqlConnection(Konekcija);

connection.Open();


MySqlCommand cmd = new MySqlCommand(komanda, connection);

Try this

    using (SqlConnection conn = new SqlConnection(Konekcija))
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Clear();
        cmd.CommandText = komanda ;
        conn.Open();
        var dataReader= cmd.ExecuteReader();

        while (result.Read())
        {
          value = dataReader["amount"].ToString();
        }


        conn.Close();

    }

If you need single value, you can use cmd.ExecuteScalar(); instead of cmd.ExecuteReader(); because ExecuteScalar() will return single value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM