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 谢谢。

 

  未完待续。^_^

posted @ 2012-08-26 19:48 Healtheon 阅读(...) 评论(...) 编辑 收藏