I’m querying a database with SQLite. I’m trying to get data from this database, save it in an array, then return to the controller. I need to present this data using a foreach loop in my view.
string sql = "select * from Tasks Where UserId = " + userId.ToString();
using (SQLiteConnection conn = new SQLiteConnection(connString))
{
SQLiteCommand cmd = new SQLiteCommand(sql, conn);
conn.Open();
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
int i = 0;
while (rdr.Read())
{
//here is what i would do in PHP
$array[$i]['name'] = $rdr[i]["name"];
$array[$i]['key'] $rdr[$i]["key"];
}
}
}
return array;
Firstly, learn to use parameterised queries not string concatenation as this will help prevent SQL injection attacks.
Also, if you create a class to represent a record in your
Taskstable then you can build instances of this object and return them in a list which will make using the code easier since instead of having untyped arrays, you will have an object with properties (in your view you can doforeach (var task in Model)whereModelis aList<Task>.Instead of writing all the query logic and creating objects, you can use frameworks called
Object Relational Mappers (ORM)to do this for you. There are a number of them around, some more simple than others. A MicroORM may suit your purposes, they are simple and easy to use (I have built one called MicroLite but there are others such as dapper or PetaPoco. If you want something more powerful, NHibernate and Entity Framework are popular choices.