Xamarin.Forms SQLite.net数据执行

时间:2015-07-21 14:21:55

标签: c# sqlite mobile xamarin xamarin.forms

我在Sqlite Browser中使用导入的Excel文件生成SQLite数据库。 它有几张桌子。每个表具有相同的结构。

列是:

  • 年龄
  • 2000米
  • 2000F
  • 2500米
  • 250°F
  • ......等。

我只需要在我的Xamarin.Forms共享项目中打开这个数据库,每次执行1项。

每个单元格包含1个双号。我需要执行此号码并将其发送到屏幕上的标签。

我不需要向此数据库写任何内容。只读。

我能想象的最好的方法是执行SQL,如:

Select 2000m From Bravo Where Age = 20.

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

问题出在Windows Phone上。不知怎的,它无法启动SQLiteConnection。 但Android确实如此,因此iOS也必须如此。

首先,我将数据库移至本地应用程序路径:

 public static string GetLocalFilePath(string filename)
        {
            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string dbPath = Path.Combine(path, filename);

            CopyDatabaseIfNotExists(dbPath);

            return dbPath;
        }

        private static void CopyDatabaseIfNotExists(string dbPath)
        {
            if (!File.Exists(dbPath))
            {
                using (var br = new BinaryReader(Application.Context.Assets.Open("KDLife_mobileDB.db3")))
                {
                    using (var bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
                    {
                        byte[] buffer = new byte[2048];
                        int length = 0;
                        while ((length = br.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            bw.Write(buffer, 0, length);
                        }
                    }
                }
            }
        }

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            global::Xamarin.Forms.Forms.Init (this, bundle);
            global::Xamarin.FormsMaps.Init(this, bundle);

            string dbPath = GetLocalFilePath("KDLife_mobileDB.db3");

            LoadApplication (new KDLife_mobile.App ());

            App.ScreenWidth = (int)Resources.DisplayMetrics.WidthPixels;
            App.ScreenHeight = (int)Resources.DisplayMetrics.HeightPixels;


        }

然后我打开了连接:

public SQLiteConnection DBClass_conn()
        {
            database = new SQLiteConnection (DatabasePath);
            return database;
        }

然后我添加了SQLiteCommand:

SQLiteCommand cmd = new SQLiteCommand(App.Database.DBClass_conn());

并查询:

public string querytext(string q_table)
        {
            string sql = "SELECT \"2000f\" FROM Bravo WHERE Age = \"20\" AND Period = \"15\"";//, App.amount_gender, q_table, App.age;
            return sql;
        }

然后我只需更改CommandText和ExecuteScalar:

cmd.CommandText = querytext("Symphony");
string count = (string)cmd.ExecuteScalar<string>();

现在它只执行1个查询,但要让它更具普遍性并不难。

相关问题