[英]How to get data from database? SQLite on Winrt
我在项目文件夹中准备了现成的.db数据库,其中包含“ city”,“ area”字段和添加的数据。
那么,如何从其中city ==一些值的数据库中获取信息?
我使用C#,sqlite-net和SQLite。
假设您有以下单个表数据库,如下所示:
-现在,需要根据您的需要和数据库的大小将“ .db ”文件复制到Local (或Roaming )文件夹中,将以下方法添加到App.xaml.cs文件中
private async Task CopyDatabase()
{
bool isDatabaseExisting = false;
try
{
var s = ApplicationData.Current.LocalFolder.Path;
StorageFile storageFile
= await ApplicationData.Current.LocalFolder.GetFileAsync("DataBase.db");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
StorageFile databaseFile = await
Package.Current.InstalledLocation.GetFileAsync(@"Data\DataBase.db");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
}
上面的代码会将数据库从InstalledLocation( Appx )复制到本地文件夹 ,
安装包SQLitePCL
使用该Vs扩展名添加对Windows运行时(Windows 8.1)的SQLite的引用
添加数据模型:为数据库中的每个表创建一个拥有相同结构的类,这里我们只有一个表' Data
':
public class Data { public long Id { get; set; } public String City { get; set; } public String Area { get; set; } }
添加一个包含所有数据交互逻辑的类,并使用Sqlite.netPcl
lib对数据库添加所有必需的操作:
public class DataService { private readonly SQLiteConnection _connection; public DataService() { _connection = new SQLiteConnection("DataBase.db"); } public async Task<List<Data>> GetAllCities() { var cities = new List<Data>(); using (var statement = _connection.Prepare("SELECT * FROM Data")) { while (statement.Step() == SQLiteResult.ROW) { cities.Add(new Data() { Id = (long)statement[0], City = (string)statement[1], Area = (string)statement[2] }); } } return cities; }
}
这里不需要async
方法,但是您可以考虑在高级方案中,
最后,只需调用GetAllCities
方法即可获取数据:
public async void MainPage_OnLoaded(object sender, RoutedEventArgs routedEventArgs) { var dataService=new DataService(); ListV.ItemsSource = await dataService.GetAllCities(); }
Xaml:
<ListView x:Name="ListV" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding City}"/>
<TextBlock Text="{Binding Area}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.