引用组件
sqlite-net-pcl
1.创建/获取数据库(表)
static TodoItemDatabase database;
public static TodoItemDatabase Database
{
get
{
if (database == null)
{
database = new TodoItemDatabase(DependencyService.Get<IFileHelper>().GetLocalFilePath("TodoSQLite.db3"));
}
return database;
}
}
public TodoItemDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<TodoItem>().Wait();
}
2.查询
return database.QueryAsync<TodoItem>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
return database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
3.保存
public Task<int> SaveItemAsync(TodoItem item)
{
if (item.ID != 0)
{
return database.UpdateAsync(item);
}
else {
return database.InsertAsync(item);
}
}
4.删除
public Task<int> DeleteItemAsync(TodoItem item)
{
return database.DeleteAsync(item);
}
5.获取地址
//android
[assembly: Dependency(typeof(FileHelper))]
namespace Todo.Droid
{
public class FileHelper : IFileHelper
{
public string GetLocalFilePath(string filename)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return Path.Combine(path, filename);
}
}
}
//ios
[assembly: Dependency(typeof(FileHelper))]
namespace Todo.iOS
{
public class FileHelper : IFileHelper
{
public string GetLocalFilePath(string filename)
{
string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
return Path.Combine(libFolder, filename);
}
}
}