簡體   English   中英

如何從數據庫獲取數據? Winrt上的SQLite

[英]How to get data from database? SQLite on Winrt

我在項目文件夾中准備了現成的.db數據庫,其中包含“ city”,“ area”字段和添加的數據。
那么,如何從其中city ==一些值的數據庫中獲取信息?
我使用C#,sqlite-net和SQLite。

假設您有以下單個表數據庫,如下所示:

數據庫架構

  • 將數據庫“ .db”文件添加到您的項目中,我選擇將其放在“ 數據文件夾”中以保持項目的結構化,
  • 將數據庫文件的構建操作設置為內容,以便在編譯時將其復制到AppX文件中,

建立行動 -現在,需要根據您的需要和數據庫的大小將“ .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 )復制到本地文件夾

  • OnLaunched方法中調用以下方法: 在此處輸入圖片說明

  • 為了讓您對數據庫執行SQL查詢,有幾種方法其中之一是使用SQLitePCL庫,所以把它添加到您的使用項目的NuGet

安裝包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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM