我正在创建一个dot net maui android应用程序。该应用程序需要访问一个预先填充的sqlite数据库,并检索问题列表。我有数据库,我似乎是正确的链接到应用程序,但我无法检索数据。
这就是我对数据的要求:
private async Task<List<TodoItem>> RetrieveFromDatabase()
{
try
{
var compDatabase = new CompDatabase();
var questions = await compDatabase.GetItemsAsync();
Console.WriteLine("Lines retrieved: " + questions.Count);
return questions;
}
catch (Exception ex)
{
Console.WriteLine("Error retrieving questions: " + ex.Message);
// Handle any exceptions here
return new List<TodoItem>();
}
}
[DOTNET]检索到的行:0
下面是基于micros soft的例子:https://github.com/dotnet/maui-samples/blob/main/7.0/Data/TodoSQLite/TodoSQLite/Data/TodoItemDatabase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
using Comp.Models;
namespace Comp.Data
{
public class CompDatabase
{
SQLiteAsyncConnection Database;
public CompDatabase()
{
}
async Task Init()
{
if (Database is not null)
return;
Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
var result = await Database.CreateTableAsync<TodoItem>();
}
public async Task<List<TodoItem>> GetItemsAsync()
{
await Init();
Console.WriteLine("Database path: " + Constants.DatabasePath);
Console.WriteLine("Database file exists: " + File.Exists(Constants.DatabasePath));
return await Database.Table<TodoItem>().ToListAsync();
}
public async Task<List<TodoItem>> GetItemsNotDoneAsync()
{
await Init();
return await Database.Table<TodoItem>().Where(t => t.IsAnsweredCorrectly).ToListAsync();
// SQL queries are also possible
//return await Database.QueryAsync<TodoItem>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
}
public async Task<TodoItem> GetItemAsync(int id)
{
await Init();
return await Database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
}
public async Task<int> SaveItemAsync(TodoItem item)
{
await Init();
if (item.ID != 0)
{
return await Database.UpdateAsync(item);
}
else
{
return await Database.InsertAsync(item);
}
}
public async Task<int> DeleteItemAsync(TodoItem item)
{
await Init();
return await Database.DeleteAsync(item);
}
}
}
[DOTNET]数据库路径:/data/user/0/com.companyname.comp/files/Databases/TodoSQLite.db3
[DOTNET]数据库文件存在:真
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
namespace Comp.Databases
{
public static class Constants
{
public const string DatabaseFilename = "TodoSQLite.db3";
public const SQLite.SQLiteOpenFlags Flags =
SQLite.SQLiteOpenFlags.ReadWrite |
SQLite.SQLiteOpenFlags.Create |
SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath
{
get
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(basePath, "Databases", DatabaseFilename); // Make sure the path includes "Databases" folder
}
}
}
}
我不明白,似乎不能找到的原因,为什么我不能检索数据。根据我的控制台日志数据库正在传递到Android模拟器,所以它应该是可访问的,我没有得到任何错误。
1条答案
按热度按时间3zwtqj6y1#
希望这有帮助
MauiProgram.cs
SQLConnection.cs