database - Xamarin 表单中的本地 SQLite 数据库
问题描述
所以我使用“DB Browser for SQLite”在Xamarin Forms之外做了一个示例数据库,并将其放入Assets File
我正在尝试学习如何将我的数据库连接到它,所以我这样做了:
XAML:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="Behoerdensprache.Pages.FinanzAmt"> <ContentPage.Content> <StackLayout> <Label Text="Welcome to Xamarin.Forms!" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" x:Name="LabelControl"/> <Entry Placeholder="Search" x:Name="SearchEntry"/> <Button Text="Press me" Clicked="Button_Clicked"/> </StackLayout> </ContentPage.Content> </ContentPage>
C# 按钮代码:
private void Button_Clicked(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection(App.DataBaseLocation);
conn.CreateTable<Wortschatz>();
var gets = conn.Table<Wortschatz>().Where(i => i.Wort == SearchEntry.Text).ToString();
LabelControl.Text = gets;
conn.Close();
}
App.DataBaseLocation在 Mainactivity 和 AppDelegate 中定义:
在主要活动中:
string dbName = "BeamtenSprache.sqlite";
string folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string fullPath = Path.Combine(folderPath, dbName);
LoadApplication(new App(fullPath));
在 AppDelegate 中:
string dbName = "wortschatz.sqlite";
string folderPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "..", "Library");
string fullPath = Path.Combine(folderPath, dbName);
LoadApplication(new App(fullPath));
new App(fullPath)这部分我在 App.cs 中定义:
public static string DataBaseLocation = string.Empty;
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
public App(string databaseLocation)
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
DataBaseLocation = databaseLocation;
}
但是当我运行应用程序并按下按钮时,这显示:
解决方案
xamarin.forms.samples 中有一个Todo示例项目,展示了如何在本地 SQLite 数据库中存储和访问数据。
在Androiddb file
项目中,他把Todo/Todo.Android/Resources/raw/
在iOSdb file
项目中,他把Todo/Todo.iOS/Resources/
然后他得到了db path
:
public static class Constants
{
public const string DatabaseFilename = "TodoSQLite.db3";
public static string DatabasePath
{
get
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(basePath, DatabaseFilename);
}
}
}
您可以下载它并尝试使用项目中的代码。有关更多信息,您可以阅读文档。
如果你不能解决问题,你可以在这里分享你的项目,我会检查它:)。
推荐阅读
- google-sheets-formula - 在现有公式中增加图纸编号
- sql - Laravel 查询 - 从 3 个不同的表中计数和分组
- symfony - Symfony 4 和 Mercure 与 Docker - 无法连接到服务器
- python - Django ValueError - 没有足够的值来解包(预期 2,得到 1)元组错误列表
- python - 如何绕过 Python 请求“请求远程结束关闭连接而没有响应”的错误
- php - SQL Server查询返回输出参数为空白数组
- bash - 提取数字并使用 sed 重新插入
- c++ - 如何正确编写mysql查询?
- javascript - 如何正确更改状态?(只读错误)
- java - SpringBoot如何通过嵌套属性查找记录