2011-02-08 54 views
17

一个例子任何人都可以点我使用SQLite与MonoDroid的例子吗?我甚至找不到一个。需要的SQLite与MonoDroid的

+0

如果您需要使用SQLite的工作技巧我也写了一篇博客文章在这里:http://www.elucidsoft.com/blog/2011/12/31/mono-android-working-with-sqlite/ – emalamisura 2012-01-06 17:06:21

回答

36

我显然需要一个SQLite演示添加到ApiDemo样品。

因为我不知道什么时候那会发生,这里的快速和肮脏的版本:

但是,使用下面的代码,你必须针对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(); 
+1

非常感谢!这是我缺少的链接。 – basheps 2011-02-09 17:50:49