2011-02-08 10 views
17

誰かがMonodroidでsqliteを使用する例を教えていただけますか?私は1つでも見つけられませんでした。Monodroidでsqliteの例が必要です

+0

を私もブログ記事を書きましたここに:http://www.elucidsoft.com/blog/2011/12/31/mono-android-working-with-sqlite/ – emalamisura

答えて

36

明らかに、SQLiteデモをApiDemoサンプルに追加する必要があります。

ことが起こるだろうとき、私は知らないので、ここでは、迅速かつ汚いバージョンです:

は、次のコードを使用して、ただし Mono.Dataを使用するには、Android 2.2以降をターゲットにする必要があります。 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コード:あなたはSQLiteのでの作業のヒントが必要な場合は

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

+1

+1に感謝します。これは私にとっても欠けているリンクでした。 –

+0

MonoにSystem.IOが存在しませんアンドロイド用AndroidのアプリケーションにMonoを使用するにはどうすればよいですか? – dinesh

関連する問題