在Xamarin.iOS項目中使用預設數據庫

在Xamarin.iOS項目中使用預設數據庫

當開發者準備好一個預設數據庫文件後,就能夠將這個數據庫文件添加到建立的項目中了。本節將分別在Xamarin.iOS和Xamarin.Android項目中使用預設數據庫。sql

在Xamarin.iOS項目中使用

在Xamarin.iOS項目中使用預設數據庫的具體操做步驟以下:數據庫

(1)建立一個Xamarin.iOS項目,如iOSSQLiteDemo。ide

(2)將上一節中建立的Documents.db數據庫拖動iOSSQLiteDemo項目的Resources文件夾中。spa

(3)打開ViewController.cs文件,將Documents.db數據庫複製到或移動到Documents目錄下,代碼以下:code

using Foundation;

using System;

using System.IO;

using UIKit;

namespace iOSSQLiteDemo

{

    public partial class ViewController : UIViewController

    {

                   public ViewController (IntPtr handle) : base (handle)

                   {

                   }

 

                   public override void ViewDidLoad ()

                   {

                            base.ViewDidLoad ();

            // Perform any additional setup after loading the view, typically from a nib.

            var projectBundle = NSBundle.MainBundle;

            var resourcePath = projectBundle.PathForResource("Documents", "db");

            var dirManager = NSFileManager.DefaultManager;

            string sqlitePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDocuments.db");

            Console.WriteLine("數據庫文件目錄:{0}", sqlitePath);

            NSError er = new NSError();

            dirManager.Copy(resourcePath, sqlitePath, out er);                             //複製

        }

        public override void DidReceiveMemoryWarning ()

                   {

                            base.DidReceiveMemoryWarning ();

                            // Release any cached data, images, etc that aren't in use.

                   }

    }

}

運行程序後,會在輸出窗口輸出如下的內容:orm

數據庫文件目錄:/Users/mac/Library/Developer/CoreSimulator/Devices/77752D53-9F0F-400C-89BD-A88D1EFD910C/data/Containers/Data/Application/DBD889F8-BB9A-423A-A729-E659A794B18B/Documents/MyDocuments.dbsqlite

相關文章
相關標籤/搜索