了解 Xamarin.Forms 创建移动应用程序的基础知识 11 - SQLite数据库

简介

演示 SQLite 数据库访问与数据操作。

  1. SQLite 类库引用。
  2. 操作类与数据模型。
  3. 数据操作。

SQLite 类库引用

  1. 管理 NuGet 包。
  2. 搜索 sqlite-net-pcl。
  3. 安装推荐版本。

操作类与数据模型

  1. 添加 Note.cs 到 Models 文件夹。
  2. 编辑 Note.cs:
using System;
using SQLite;
namespace AwesomeApp.Models
{
   
	public class Note
	{
   
		[PrimaryKey, AutoIncrement]
		public int ID {
    get; set; }
		public string Name {
    get; set; }
		public string Text {
    get; set; }
		public DateTime Date {
    get; set; }
		public string DateString
		{
   
			get
			{
   
				return Date.ToString();
			}
		}
	}
}
  • PrimaryKey 属性标签表示为主键
  • AutoIncrement 属性标签表示为自增列
  1. 添加 NoteDatabase.cs 到 Data 文件夹。
  2. 编辑 NoteDatabase.cs:
using AwesomeApp.Models;
using SQLite;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AwesomeApp.Data
{
   
	public class NoteDatabase
	{
   
		private readonly SQLiteAsyncConnection _database;
		public NoteDatabase(string dbPath)
		{
   
			_database = new SQLiteAsyncConnection(dbPath);
			_database.CreateTableAsync<Note>().Wait();
		}
		~NoteDatabase()
		{
   
			_database.CloseAsync();
		}
		public Task<List<Note>> GetNotesAsync()
		{
   
			return _database.Table<Note>().ToListAsync();
		}
		public Task<Note> GetNoteAsync(int id)
		{
   
			return _database.Table<Note>()
							.Where(i => i.ID == id)
							.FirstOrDefaultAsync();
		}
		public Task<int> SaveNoteAsync(Note note)
		{
   
			if (note.ID != 0)
			{
   
				return _database.UpdateAsync(note);
			}
			else
			{
   
				return _database.InsertAsync(note);
			}
		}
		public Task<int> DeleteNoteAsync(Note note)
		{
   
			return _database.DeleteAsync(note);
		}
	}
}
  1. 编辑 App.xaml.cs:
static NoteDatabase database;
public static NoteDatabase Database
{
   
	get
	{
   
		if (database == null)
		{
   
			database = new NoteDatabase
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值