Có ai có thể chỉ cho tôi một ví dụ về cách sử dụng sqlite với Monodroid không? Tôi đã không thể tìm thấy ngay cả một.Cần một ví dụ về sqlite với Monodroid
17
A
Trả lời
36
Tôi rõ ràng cần thêm bản trình diễn SQLite vào mẫu ApiDemo.
Vì tôi không biết khi nào điều đó sẽ xảy ra, đây là phiên bản nhanh chóng và dơ bẩn:
Tuy nhiên, để sử dụng đoạn mã sau bạn phải được nhắm mục tiêu điều hành Android 2.2 hoặc mới hơn để sử dụng Mono.Data. Sqlite. Nếu bạn cần nhắm mục tiêu phiên bản Android cũ hơn, bạn nên xem xét một thay thế được quản lý hoàn toàn, chẳng hạn như managed-sqlite.
Hơn nữa, ví dụ này đang sử dụng Mono.Data.Sqlite.dll, được bao gồm trong SDK MonoDroid.
Trước tiên, hãy chỉnh sửa tham chiếu lắp ráp dự án của bạn và thêm tham chiếu cho Mono.Data.Sqlite.dll
và System.Data.dll
.
Thứ hai, bên trong mã nguồn của bạn, thêm:
using System.Data;
using Mono.Data.Sqlite;
Cuối cùng, sử dụng các ngươi bình thường mã 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();
Nếu bạn cần lời khuyên về làm việc với SQLite Tôi cũng đã viết một bài viết trên blog tại đây: http://www.elucidsoft.com/blog/2011/12/31/mono-android-working-with-sqlite/ – emalamisura