Android in Mono開發初體驗之DataBase


  本文給大家介紹在MonoDevelop環境下操作SQLite數據庫的功能,使得在Android中方便的實現對數據的增、刪、改、查功能。

  

  數據存儲在開發中的重要性我就不再多說了,你懂的。關於Android中的數據存儲技術有興趣或需要的朋友可以查看我以前的一篇博文:http://www.cnblogs.com/hanyonglu/archive/2012/03/01/2374894.html 

  今天這個示例是給大家展示在MonoDevelop中操作Sqlite數據庫的功能。關於Sqlite數據庫大家仍然可以查看我以前的那篇文章,這里不再詳述。如果有Android基礎的朋友一看這篇文章就能明白,畢竟和用JAVA開發的原理都是一樣的;如果沒有Android基礎的朋友,那么希望這篇文章能給你帶來幫助,不過需要明白的是這篇文章是在MonoDevelop中開發的。

  

  首先,我們需要先在MonoDevelop中新建一個解決方案。然后新建一個類命名為:DataBaseHelper。其代碼如下所示:

using System;

using Android.Database.Sqlite;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.IO;

namespace MyDataDemo
{
    /// <summary>
    /// Data base helper.
    /// Description:數據庫操作類
    /// Author:Hanyonglu
    /// Date:2012-08-26 15:30:56
    /// </summary>
    public class DataBaseHelper
    {
        // Sqlite數據庫對象
        private SQLiteDatabase dataBase;
        private string strQuery;
        // 程序跟蹤消息
        private string message;
        private bool isAvailable;

        public DataBaseHelper ()
        {
        }

        /// <summary>
        /// 構造器創建數據庫
        /// </summary>
        /// <param name='dataBaseName'>
        /// Data base name.
        /// </param>
        public DataBaseHelper (string dataBaseName)
        {
            try
            {
                CreateDatabase (dataBaseName);
            }
            catch (SQLiteException ex)
            {
                message = ex.Message;
            }
        }

        /// <summary>
        /// 獲取或設置程序跟蹤消息
        /// </summary>
        /// <value>
        /// The message.
        /// </value>
        public string Message 
        {
            get{ return message;}
            set{ message = value;}
        }

        /// <summary>
        /// 獲取或設置數據庫是否可用的狀態
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is available; otherwise, <c>false</c>.
        /// </value>
        public bool IsAvailable 
        {
            get{ return isAvailable;}
            set{ isAvailable = value;}
        }

        /// <summary>
        /// 創建數據庫
        /// </summary>
        /// <param name='dataBaseName'>
        /// Data base name.
        /// </param>
        public void CreateDatabase (string dataBaseName)
        {
            try 
            {
                message = "";
                string location = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
                string dataBasePath = Path.Combine (location, dataBaseName);
                bool isExistDataBase = File.Exists (dataBasePath);        

                if (!isExistDataBase) 
                {
                    // 如果數據庫不存在則直接創建數據庫
                    dataBase = SQLiteDatabase.OpenOrCreateDatabase (dataBasePath, null);
                    // 創建數據表
                    strQuery = "CREATE TABLE " + 
                        "IF NOT EXISTS MyContacts " +
                        "(_id INTEGER PRIMARY KEY AUTOINCREMENT,Name VARCHAR,Tel INT,Address VARCHAR);";
                    dataBase.ExecSQL (strQuery);
                    message = "創建數據庫";
                } 
                else
                {
                    // 如果數據庫存在直接打開
                    dataBase = SQLiteDatabase.OpenDatabase (dataBasePath, null, DatabaseOpenFlags.OpenReadwrite);
                    message = "打開數據庫";
                }

                isAvailable = true;
            } 
            catch (SQLiteException ex) 
            {
                message = ex.Message;
            }
        }

        /// <summary>
        /// 添加一個新聯系人信息
        /// </summary>
        /// <param name='name'>
        /// Name.
        /// </param>
        /// <param name='tel'>
        /// Tel.
        /// </param>
        /// <param name='address'>
        /// Address.
        /// </param>
        public void AddNewPerson (string name, int tel, string address)
        {
            try
            {
                strQuery = "INSERT INTO MyContacts (Name,Tel,Address)" +
                    "VALUES('" + name + "'," + tel + ",'" + address + "');";
                dataBase.ExecSQL (strQuery);
                message = "增加了一個新聯系人的信息";
            }
            catch (SQLiteException ex) 
            {
                message = ex.Message;
            }
        }

        /// <summary>
        /// 根據id更新一個聯系人信息
        /// </summary>
        /// <param name='id'>
        /// Identifier.
        /// </param>
        /// <param name='name'>
        /// Name.
        /// </param>
        /// <param name='tel'>
        /// Tel.
        /// </param>
        /// <param name='address'>
        /// Address.
        /// </param>
        public void UpdatePerson (int id, string name, int tel, string address)
        {
            try
            {
                strQuery = "UPDATE MyContacts SET Name='" + name + "',Tel='" + tel + "',Address='" + address + "' " +
                    "WHERE _id='" + id + "';";
                dataBase.ExecSQL (strQuery);
                message = "更新了一個聯系人的信息";
            } 
            catch (SQLiteException ex) 
            {
                message = ex.Message;
            }
        }

        /// <summary>
        /// 根據id刪除一個聯系人信息
        /// </summary>
        /// <param name='id'>
        /// Identifier.
        /// </param>
        public void DeletePerson (int id)
        {
            try 
            {
                strQuery = "DELETE FROM MyContacts WHERE _id='" + id + "';";
                dataBase.ExecSQL (strQuery);
                message = "刪除了一個聯系人的信息";
            }
            catch (SQLiteException ex) {
                message = ex.Message;
            }
        }

        /// <summary>
        /// 獲取所有聯系人信息
        /// </summary>
        /// <returns>
        /// The all persons.
        /// </returns>
        public Android.Database.ICursor GetAllPersons ()
        {
            Android.Database.ICursor cursor = null;

            try {
                strQuery = "SELECT * FROM MyContacts;";
                cursor = dataBase.RawQuery (strQuery, null);

                if (cursor != null)
                {
                    message = "獲取所有聯系人的信息";
                }
                else
                {
                    message = "未找到相應的聯系人的信息";
                }
            } 
            catch (SQLiteException ex)
            {
                message = ex.Message;
            }

            return cursor;
        }

        /// <summary>
        /// 根據模糊查詢獲取聯系人信息
        /// </summary>
        /// <returns>
        /// The like person.
        /// </returns>
        /// <param name='content'>
        /// Content.
        /// </param>
        /// <param name='value'>
        /// Value.
        /// </param>
        public Android.Database.ICursor GetLikePersons (string content, string value)
        {
            Android.Database.ICursor cursor = null;

            try 
            {
                strQuery = "SELECT * FROM MyContacts WHERE " + content + " LIKE '%" + value + "%';";
                cursor = dataBase.RawQuery (strQuery, null);

                if (cursor != null)
                {
                    message = "獲取模糊查詢的聯系人的信息";
                }
                else
                {
                    message = "未找到相應的聯系人的信息";
                }
            }
            catch (SQLiteException ex)
            {
                message = ex.Message;
            }

            return cursor;
        }

        /// <summary>
        /// 釋放資源
        /// <see cref="MyDataDemo.DataBaseHelper"/> is reclaimed by garbage collection.
        /// </summary>
        ~DataBaseHelper()
        {
            try {
                message = null;
                isAvailable = false;        
                dataBase.Close ();        
            } catch (SQLiteException ex) {
                message = ex.Message;
            }
        }
    }
}

 

  最后,希望轉載的朋友能夠尊重作者的勞動成果,加上轉載地址:http://www.cnblogs.com/hanyonglu/archive/2012/08/26/2657648.html 謝謝。

 

  未完待續。^_^


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM