SQLite

引用组件

sqlite-net-pcl

1.创建/获取数据库(表)

static TodoItemDatabase database;

public static TodoItemDatabase Database
{
  get
  {
    if (database == null)
    {
      database = new TodoItemDatabase(DependencyService.Get().GetLocalFilePath("TodoSQLite.db3"));
    }
    return database;
  }
}
public TodoItemDatabase(string dbPath)
{
  database = new SQLiteAsyncConnection(dbPath);
  database.CreateTableAsync().Wait();
}

2.查询

return database.QueryAsync("SELECT * FROM [TodoItem] WHERE [Done] = 0");
return database.Table().Where(i => i.ID == id).FirstOrDefaultAsync();

3.保存

public Task SaveItemAsync(TodoItem item)
{
  if (item.ID != 0)
  {
    return database.UpdateAsync(item);
  }
  else {
    return database.InsertAsync(item);
  }
}

4.删除

public Task 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);
        }
    }
}

你可能感兴趣的:(SQLite)