需要一个带有Monodroid的sqlite的例子

时间:2011-02-08 21:47:53

标签: c# android sqlite xamarin.android

有人能指出我在Monodroid中使用sqlite的例子吗?我甚至找不到一个。

1 个答案:

答案 0 :(得分:36)

我显然需要在ApiDemo示例中添加一个SQLite演示。

因为我不知道什么时候会发生,所以这是快速而肮脏的版本:

但是,要使用以下代码,必须定位Android 2.2或更高版本才能使用Mono.Data.Sqlite。如果您需要定位较早的Android版本,则应该查看完全托管的替代版本,例如managed-sqlite

此外,此示例使用的是Mono.Data.Sqlite.dll,它包含在MonoDroid SDK中。

首先,编辑项目程序集引用并添加Mono.Data.Sqlite.dllSystem.Data.dll的引用。

其次,在源代码中添加:

using System.Data;
using Mono.Data.Sqlite;

最后,使用正常的ADO.NET代码:

string dbPath = Path.Combine (
        Environment.GetFolderPath (Environment.SpecialFolder.Personal),
        "items.db3");
bool exists = File.Exists (dbPath);
if (!exists)
    SqliteConnection.CreateFile (dbPath);
var connection = new SqliteConnection ("Data Source=" + dbPath);
connection.Open ();
if (!exists) {
    // This is the first time the app has run and/or that we need the DB.
    // Copy a "template" DB from your assets, or programmatically create one.
    var commands = new[]{
        "CREATE TABLE [Items] (Key ntext, Value ntext);",
        "INSERT INTO [Items] ([Key], [Value]) VALUES ('sample', 'text')"
    };
    foreach (var command in commands) {
        using (var c = connection.CreateCommand ()) {
            c.CommandText = command;
            c.ExecuteNonQuery ();
        }
    }
}
// use `connection`...
// here, we'll just append the contents to a TextView
using (var contents = connection.CreateCommand ()) {
    contents.CommandText = "SELECT [Key], [Value] from [Items]";
    var r = contents.ExecuteReader ();
    while (r.Read ())
        MyTextView.Text += string.Format ("\n\tKey={0}; Value={1}",
                r ["Key"].ToString (), r ["Value"].ToString ());
}
connection.Close ();
相关问题