How to make a Foreach in a SQLite DataReader?

0

I'm trying to get the data from an SQLite query and then save the fields in a list and show them to the user through a MessageBox. I have two problems: 1) I do not know if what I'm doing is fine. 2) I do not compile the code, and I do not know why!

Here I leave what I have:

        var lista= new List<string>();

        string nombre = "";
        string mesa = this.numMesa.Trim();
        String consulta_productos = "Select nombre from Productos where mesa = @mesa";
        SQLiteCommand comd = new SQLiteCommand(consulta_productos, conexion);
        comd.Parameters.Clear();
        comd.Parameters.Add(new SQLiteParameter("@mesa", mesa));
        comd.ExecuteNonQuery();
        using (SQLiteDataReader read = comd.ExecuteReader())
        {
                foreach (string i in read)
                {
                    // acá me tira error
                    lista.Add(read.GetString(i));
                }
        }

The compiler throws me an error that says "can not convert string to int" in the line that I frame above. I do not understand why. Try putting i.toString () and it does not compile either.

Is the foreach well done? And what do you mean you can not convert string to int if I do not have any int? : /

    
asked by Nacho Zve De La Torre 26.06.2018 в 04:14
source

1 answer

1

The parameter of .GetString() is an integer corresponding to the column number (starting at 0) of the result. This column number can be calculated based on the name of the column by .GetOrdinal("nombreDeColumna")

In your case, replace the foreach with the following:

while (read.Read())
{
    lista.Add(read.GetString(read.GetOrdinal("nombre")));
}

Also the comd.ExecuteNonQuery(); does not make sense since what you are executing is precisely a query. Just delete it.

comd.Parameters.Clear(); is another line that is over, if you just instantiate the SQLiteCommand has no parameter so it does not make sense to clean it.

You can also take advantage of using var instead of repeating the data type in some places.

You can also take advantage of object initializers to scan the code more compactly.

Everything can be done in the following way:

var consultaProductos = "Select nombre from Productos where mesa = @mesa";
using (var comd = new SQLiteCommand(consultaProductos, conexion)
{
    Parameters =
    {
        new SQLiteParameter("@mesa", mesa)
    }
})
{
    using (var read = comd.ExecuteReader())
    {
        while (read.Read())
        {
            lista.Add(read.GetString(read.GetOrdinal("nombre")));
        }
    }
}
    
answered by 26.06.2018 / 07:02
source