skip to Main Content

In this code, I cannot find the problem, can someone help me?

int getids;
using (var SqlCommand = new MySqlCommand($"SELECT a.id+1 AS start FROM table AS a, table AS b WHERE a.id < b.id GROUP BY a.id HAVING start < MIN(b.id) LIMIT 1", Program.SQL.conn))
{
    var check = SqlCommand.ExecuteReader();
    if (check.HasRows)
    {
        check.Read();
        getids = Convert.ToInt32(check["id"]);
        check.Close();

The error I get is:

Exception IndexOutOfRangeException: Could not find specified column in results: id

But the table exists and the columns as well, the query in phpMyAdmin works smoothly, so how do I check the field id in C#?

2

Answers


  1. You are returning a single row with a single column. This is the exact scenario where you use ExecuteScalar instead of an ExecuteReader.
    Just remember that your query could return null (there is a WHERE and an HAVING condition). So you need to check the return from ExecuteScalar before converting it to an integer

    int getids;
    using (var SqlCommand = new MySqlCommand($"SELECT a.id+1 AS start FROM table AS a, table AS b WHERE a.id < b.id GROUP BY a.id HAVING start < MIN(b.id) LIMIT 1", Program.SQL.conn))
    {
        var check = SqlCommand.ExecuteScalar();
        if(check != null)
            getids = Convert.ToInt32(check);
    }
    
    Login or Signup to reply.
  2. You have

    "SELECT a.id+1 AS start..."
    

    So you id became start

    getids = Convert.ToInt32(check["start"]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search