我正在使用 SQLite 查询数据库。我正在尝试从数据库中获取数据,将其保存在数组中并返回到控制器。然后我需要在我的视图中使用 foreach 来呈现这些数据。
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;
Run Code Online (Sandbox Code Playgroud)
请帮助使用 while 代码。
首先,学习使用参数化查询而不是字符串连接,因为这将有助于防止 SQL 注入攻击。
string sql = "select * from Tasks Where UserId = @userId";
Run Code Online (Sandbox Code Playgroud)
此外,如果您创建一个类来表示Tasks表中的记录,那么您可以构建此对象的实例并将它们返回到一个列表中,这将使代码的使用更容易,因为您将拥有一个带有属性的对象(而不是无类型数组)(在您看来,您可以执行foreach (var task in Model)where Modelis a List<Task>。
public class Task
{
public int Id { get; set; }
public string Name { get; set; }
public string Key { get; set; }
}
var tasks = new List<Task>(); // create a list to populate with tasks
using (var connection = new SQLiteConnection(connString))
{
var command = new SQLiteCommand(sql, conn);
command.Parameters.Add("@userId", userId); // only do .ToString on userId if the column is a string.
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var task = new Task();
task.Id = (int)reader["id"]; // the name of the column in the reader will match the column in the Tasks table.
task.Name = (string)reader["name"];
task.Key = (string)reader["key"];
tasks.Add(task);
}
}
}
return tasks;
Run Code Online (Sandbox Code Playgroud)
无需编写所有查询逻辑和创建对象,您可以使用被调用的框架Object Relational Mappers (ORM)来为您执行此操作。周围有很多,有些比其他的更简单。MicroORM 可能适合您的目的,它们简单易用(我构建了一个名为MicroLite 的,但还有其他的,例如 dapper 或 PetaPoco。如果您想要更强大的东西,NHibernate 和实体框架是流行的选择。
| 归档时间: |
|
| 查看次数: |
4253 次 |
| 最近记录: |