Android - 无法在 Xamarin.forms 中打开数据库(SQLite 异常)
Android - Could not open database in Xamarin.forms (SQLite exceptions)
抱歉,如果之前有人问过这个问题,但我很好地搜索了这个问题,但我没有找到答案。
我在我的 Xamarin 表单项目 (PCL) 中使用 SQLite 处理本地数据库。
1- 连接在 iOS 中运行良好,但在 android 中我遇到了这个问题
(无法打开数据库文件)
- 我还设置了 "ReadExternalStoarage" 和 "WriteExternalStoarage" 权限。
2- 我使用另一种创建连接路径的方法是:
string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string path = Path.Combine(documentsPath, "pbcare.db");
这样在处理数据库的时候就出现了异常...
public bool checkLogin (string email, string password)
{
if (DB.Table<User> ().Where (user => user.Email == email && user.Password == password)
.FirstOrDefault () != null) { // exception caught here
return true;
} else {
return false;
}
}
但是 table 在数据库中。
注意:即使数据库文件不存在,第二种方式也会创建连接!
Android 将无法将 SQLite 数据库与本地系统中的文件一起使用。 path
变量必须来自 Android 系统。您用来创建路径的第二种方法是正确的:
var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
path = Path.combine(path, 'pbcare.db3');
将为 Android 上的 db3 文件创建适当的文件路径。
您提到的下一个问题:no such table: User
是由于未创建 table 引起的。在使用数据库之前,您需要创建所有必要的 tables。
var conn = new SQLiteConnection(path);
conn.CreateTable<User>();
如果您这样做并首先创建 User
table,那么它应该会按预期工作。这里有来自 Xamarin 的更深入的教程:https://developer.xamarin.com/guides/cross-platform/application_fundamentals/data/part_3_using_sqlite_orm/
抱歉,如果之前有人问过这个问题,但我很好地搜索了这个问题,但我没有找到答案。
我在我的 Xamarin 表单项目 (PCL) 中使用 SQLite 处理本地数据库。
1- 连接在 iOS 中运行良好,但在 android 中我遇到了这个问题 (无法打开数据库文件)
- 我还设置了 "ReadExternalStoarage" 和 "WriteExternalStoarage" 权限。
2- 我使用另一种创建连接路径的方法是:
string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string path = Path.Combine(documentsPath, "pbcare.db");
这样在处理数据库的时候就出现了异常...
public bool checkLogin (string email, string password)
{
if (DB.Table<User> ().Where (user => user.Email == email && user.Password == password)
.FirstOrDefault () != null) { // exception caught here
return true;
} else {
return false;
}
}
但是 table 在数据库中。
注意:即使数据库文件不存在,第二种方式也会创建连接!
Android 将无法将 SQLite 数据库与本地系统中的文件一起使用。 path
变量必须来自 Android 系统。您用来创建路径的第二种方法是正确的:
var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
path = Path.combine(path, 'pbcare.db3');
将为 Android 上的 db3 文件创建适当的文件路径。
您提到的下一个问题:no such table: User
是由于未创建 table 引起的。在使用数据库之前,您需要创建所有必要的 tables。
var conn = new SQLiteConnection(path);
conn.CreateTable<User>();
如果您这样做并首先创建 User
table,那么它应该会按预期工作。这里有来自 Xamarin 的更深入的教程:https://developer.xamarin.com/guides/cross-platform/application_fundamentals/data/part_3_using_sqlite_orm/