首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我需要一个Monodroid的sqlite示例

我需要一个Monodroid的sqlite示例
EN

Stack Overflow用户
提问于 2011-02-09 05:47:53
回答 1查看 13.6K关注 0票数 17

谁能给我举一个在Monodroid中使用sqlite的例子?我甚至找不到一个。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-09 21:50:25

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

由于我不知道什么时候会发生这种情况,这里是快速和肮脏的版本:

然而,要使用以下代码,您必须以Android2.2或更高版本为目标才能使用Mono.Data.Sqlite。如果你需要一个更早的Android版本,你应该考虑一个完全托管的替代品,比如managed-sqlite

此外,此示例使用的是MonoDroid开发工具包中包含的Mono.Data.Sqlite.dll

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

其次,在源代码中添加:

代码语言:javascript
复制
using System.Data;
using Mono.Data.Sqlite;

最后,使用普通的ADO.NET代码:

代码语言:javascript
复制
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 ();
票数 36
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4938867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档