前言
Xamarin.Forms支持使用SQLite数据库引擎。本文介绍了Xamarin.Forms应用程序如何读取和写入数据到使用SQLite.Net的本地SQLite数据库。
在Xamarin.Forms项目中引用 SQLite 包
要使用 SQLite , 我们先要引用 SQLite 的引用包。使用 NuGet 的搜索功能查找sqlite net pcl并安装最新的包:
连接 SQLite 本地数据库并创建数据表
//SQLite 数据库地址 var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite.db3"); using (SQLiteConnection con = new SQLiteConnection(path)) { }
通过以上代码,创建一个名为 "sqlite.db3" 的 SQLite 本地数据库,并进行连接操作。(本地数据库存在时,直接连接)
可以看到 SQLiteConnection 对象的 DatabasePath 的路径为:/data/user/0/com.companyname.Samples/files/.local/share/sqlite.db3 。至此我们创建本地数据库及连接本地数据库成功!
在本文中主要介绍通过 SQLite.NET ORM 操作数据库。
//SQLite 数据库地址 var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite.db3"); using (SQLiteConnection con = new SQLiteConnection(path)) { // ORM方式 con.DropTable<Student>(); con.DropTable<Subject>(); con.DropTable<StudentSubject>(); con.CreateTables<Student, Subject, StudentSubject>(); sl.Children.Add(new Label() { Text = "建表完成" }); }
通过 DropTable<T>() 删除表。
通过 CreateTable<T>() 或 CreateTables<T,T,T>() 创建表。
public class Student { [PrimaryKey] public string id { get; set; } public string name { get; set; }