在Maui中使用Sqlite
在Maui中使用SQLite,首先需要添加Maui.Data库的引用,然后可以通过Microsoft.Data.Sqlite库来操作SQLite数据库。以下是一个简单的例子,展示了如何在Maui项目中创建和使用SQLite数据库。
- 打开你的Maui项目。
- 在项目中添加对
Microsoft.Data.Sqlite
的NuGet包引用。 - 使用以下代码创建和操作SQLite数据库。
using Microsoft.Data.Sqlite;
using System.Data.SqlTypes;
namespace MauiSqliteExample
{
public class DatabaseHelper
{
private readonly string _databasePath;
public DatabaseHelper()
{
_databasePath = "my_database.db"; // SQLite数据库文件路径
}
public void CreateDatabase()
{
var connectionString = $"Filename={_databasePath}";
using var connection = new SqliteConnection(connectionString);
connection.Open();
var createTableCommand = "CREATE TABLE IF NOT EXISTS People (Id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)";
using var command = new SqliteCommand(createTableCommand, connection);
command.ExecuteNonQuery();
}
public void InsertData(string name, int age)
{
var connectionString = $"Filename={_databasePath}";
using var connection = new SqliteConnection(connectionString);
connection.Open();
var insertCommand = "INSERT INTO People (Name, Age) VALUES (@name, @age)";
using var command = new SqliteCommand(insertCommand, connection);
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@age", age);
command.ExecuteNonQuery();
}
public List<Person> GetAllPeople()
{
var people = new List<Person>();
var connectionString = $"Filename={_databasePath}";
using var connection = new SqliteConnection(connectionString);
connection.Open();
var selectCommand = "SELECT Id, Name, Age FROM People";
using var command = new SqliteCommand(selectCommand, connection);
using var reader = command.ExecuteReader();
while (reader.Read())
{
people.Add(new Person(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2)));
}
return people;
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person(int id,
评论已关闭