1. 程式人生 > >mono for android中使用dapper或petapoco對sqlite進行資料操作

mono for android中使用dapper或petapoco對sqlite進行資料操作

在mono for android中使用dapper或petapoco,很簡單,新建android 類庫專案,直接把原來的檔案複製過來,對Connection連線報錯部分進行註釋和修改就可以運行了.(用可移植類庫PCL專案也可以的.)

如果需要原始碼可以聯絡我.10元收費哈..

以下內容包括

1.在安卓中建立sqlite資料庫;

2.檢查資料庫是否存在;

3.返回資料庫路徑;

4.插入資料(前置知識,dapper的使用方法或petapoco的);

5.查詢資料;

本人小菜鳥一枚,以下程式碼寫得很爛,希望有好的想法可以指點下我.

知識點提示

1.安卓sqlite資料提交,預設每一次都是事務提交,所以如果不採用一次性全部事務提交,會造成很多事務的建立.也就是把提交部分,用一個事務包起來,不要不用事務.否則很慢.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

using System.IO;
using Mono.Data.Sqlite;
using System.Data;
using Android.Util;
using Microsoft.CSharp; using Mono.CSharp; using Dapper; using BaseModel; using PetaPocoForMobile; namespace monoandroid1.Controllers { [Activity(Label = "啟動頁", MainLauncher = true, Icon = "@drawable/icon")] public class Start : Activity { private TextView tips;
private EditText keyword; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Create your application here SetContentView(Resource.Layout.Main); tips = FindViewById<TextView>(Resource.Id.Results); Button BtCreatDatabase = FindViewById<Button>(Resource.Id.CreatDatabase); BtCreatDatabase.Click += new EventHandler(CreatDatabase); Button BtImportData = FindViewById<Button>(Resource.Id.ImportData); BtImportData.Click += delegate { ImportData(); }; Button BtDataDisplay = FindViewById<Button>(Resource.Id.DataDisplay); BtDataDisplay.Click += delegate { keyword = FindViewById<EditText>(Resource.Id.Input); tips.Text = DataDisplay(keyword.Text) == null ? "查詢不到" : DataDisplay(keyword.Text).UserName; }; Button BtCheckDatabase = FindViewById<Button>(Resource.Id.CheckDatabase); BtCheckDatabase.Click += delegate { CheckDatabase("/data/data/monoandroid1.monoandroid1/files/UserData.db3"); }; } /// <summary> /// 建立資料庫 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void CreatDatabase(object sender, EventArgs e) { string databaseName = "UserData.db3"; string dbFilePath = GetDatabaseFilePath(databaseName); bool existsDB = CheckDatabase(dbFilePath); if (existsDB == true) { SqliteConnection.CreateFile(dbFilePath); } var conn = new SqliteConnection("Data Source=" + dbFilePath); var commands = new[] { "drop table if exists dog", "create table if not exists dog (UserId integer primary key autoincrement, UserName varchar(20),Age int,Address varchar(50))", }; try { if (conn.State == ConnectionState.Broken) conn.Close(); if (conn.State == ConnectionState.Closed) { conn.Open(); } foreach (string cmd in commands) using (SqliteCommand sqlitecmd = conn.CreateCommand()) { sqlitecmd.Connection = conn; sqlitecmd.CommandText = cmd; sqlitecmd.CommandType = CommandType.Text; //conn.Open(); sqlitecmd.ExecuteNonQuery(); //conn.Close(); } tips.Text = "資料庫建立成功"; } catch (System.Exception sysExc) { tips.Text = "Exception: " + sysExc.Message; } finally { if (conn.State != ConnectionState.Closed) { conn.Close(); } conn.Dispose(); } } /// <summary> /// 返回資料庫完整路徑 /// </summary> /// <param name="databaseName">資料庫名</param> /// <returns>返回資料庫完整路徑</returns> private string GetDatabaseFilePath(string databaseName) { string documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); string dbFilePath = Path.Combine(documents, databaseName); return dbFilePath; } /// <summary> /// 檢查資料庫是否存在 /// </summary> /// <param name="dbFilePath"></param> /// <returns>true不存在,false已經存在</returns> private bool CheckDatabase(string dbFilePath) { bool exists = File.Exists(dbFilePath); if (!exists) { //SqliteConnection.CreateFile(dbFilePath); tips.Text = "資料庫不存在"; Log.Info("CreateFile", "路徑不存在資料庫,並建立資料庫"); return true; } else { tips.Text = "資料庫已經存在"; Log.Info("CreatFile", "已經存在資料庫,放棄建立"); return false; } } private SqliteConnection OpenDatabase() { string databaseName = "UserData.db3"; string dbFilePath = GetDatabaseFilePath(databaseName); //<add name="ConnectionStringName" connectionString="sever=伺服器名;database=資料庫名;User ID=使用者;Password=密碼" providerName="System.Data.SqlClient" /> //<add name="ConnectionStringName" connectionString="Data Source=伺服器名;Initial Catalog=資料庫名;User ID=使用者;Password=密碼" providerName="System.Data.SqlClient" /> string connectionstr = "Data Source=" + dbFilePath; SqliteConnection connection = new SqliteConnection(connectionstr); if (connection.State == ConnectionState.Broken) connection.Close(); if (connection.State == ConnectionState.Closed) { connection.Open(); } return connection; } /// <summary> /// 匯入資料 /// </summary> protected void ImportData() { //dapper版 // List<Dog> Dogs = new List<Dog>(); // for (int i = 0; i < 100000; i++) // { // Dogs.Add(new Dog { UserId = i, UserName = "DogName" + i.ToString(), Age = i, Address = "ADD" + i.ToString() }); // } // string sql ="INSERT INTO dog (UserId,UserName,Age,Address) VALUES (@UserId,@UserName,@Age,@Address)"; // using (SqliteConnection connection = OpenDatabase()) // { // //SqlConnection connection = GetOpenConnection(sqlconnectionString); // //插入100000條資料到資料庫 // DateTime starttime = DateTime.Now; // TimeSpan timespan; // int records = 0; // using (var trans = connection.BeginTransaction()) // { // try // { // records += connection.Execute(sql, Dogs, trans, 30, CommandType.Text); //// for (int i = 0; i < 100000; i++) //// { //// connection.Execute("INSERT INTO dog (UserId,UserName,Age,Address) VALUES (@UserId,@UserName,@Age,@Address)", //// new { );//System.Guid.NewGuid().ToString()全球唯一識別符號 (GUID) 是一個字母數字識別符號,用於指示產品的唯一性安裝。 //// } // } // catch (DataException ex) // { // trans.Rollback(); // throw ex; // } // finally // { // trans.Commit(); // timespan = DateTime.Now.Subtract(starttime);//獲取就是開始時間很結束時間差 // if (connection.State != ConnectionState.Closed) // { // connection.Close(); // } // connection.Dispose(); // tips.Text = "資料匯入完成" + timespan.ToString(); // } // } // } //petapoco版 //var db = new PetaPocoForMobile.Database(OpenDatabase()); //SqliteConnection connection = OpenDatabase() using (SqliteConnection connection = OpenDatabase()) { int records = 0; using (var db = new PetaPocoForMobile.Database(connection)) { List<Dog> Dogs = new List<Dog>(); for (int i = 0; i < 10000; i++) { Dogs.Add(new Dog { UserId = i, UserName = "DogName" + i.ToString(), Age = i, Address = "ADD" + i.ToString() }); } DateTime starttime = DateTime.Now; TimeSpan timespan; using (var ts = db.GetTransaction()) { try { //插入100000條資料到資料庫 foreach (Dog item in Dogs) { db.Insert("dog", "UserId", item);//速度稍微慢點點,沒多少差別 //db.Execute("INSERT INTO dog (UserId,UserName,Age,Address) VALUES (@0,@1,@2,@3)", item.UserId, item.UserName, item.Age, item.Address); } ts.Complete(); } catch (Exception ex) { throw ex; } finally { timespan = DateTime.Now.Subtract(starttime);//獲取就是開始時間很結束時間差 if (connection.State != ConnectionState.Closed) { connection.Close(); } connection.Dispose(); tips.Text = "資料匯入完成" + timespan.ToString(); } } } } } /// <summary> /// 根據ID查詢單條資料 /// </summary> /// <param name="keyword"></param> /// <returns></returns> protected Dog DataDisplay(string keyword) { SqliteConnection connection = OpenDatabase(); //獲取單條記錄 //var edog = connection.Query<Dog>("select * from dog where id = @Id", new { Id = 2 }).Single<Dog>(); //var edog = connection.Query<Dog>("select * from dog where UserId = @UserId", new { UserId = keyword }).SingleOrDefault<Dog>(); try { var edog = connection.Query<Dog>("select * from dog where UserId = @UserId", new { UserId = keyword }).SingleOrDefault<Dog>(); return edog; } catch (System.Exception sysExc) { //tips.Text = "Exception: " + sysExc.Message; //Log.Info("e", "Exception: " + sysExc.Message); return null; } finally { if (connection.State != ConnectionState.Closed) { connection.Close(); } connection.Dispose(); } } } }