Windows Phone(三)WP7版 " 記賬本" 開發(使用SQLite數據庫)


  使用這個SQLite數據庫太糾結了..., ( O(∩_∩)O~歡迎拍磚...) ,所有代碼砍掉了try...catch之類的東東,是為了盡可能簡約明朗的說明問題.

第一部分:  遇到的問題 :

      1. 在前一篇(Windows Phone(二) WP7數據庫連接(SQLite數據庫))我大概介紹了SQLite的使用方法,但在自己使用SQLite開發這個記賬本程序的時候卻遇到了N多問題,比如最頭疼的問題: 數據怎么從SQLite數據庫中取出來? 是的,你會說 Community.CsharpSqlite.WP.dll不就提供了一個方法嗎?  ExecuteQuery<T>()  不就可以嗎? 是的,是可以,你得這么做(代碼如下):  這個dll提供的方法實在是少的可憐,僅僅只有這一個方法,可以.Tolist(), .ToArray().ToDictionary();

   public ....ExecuteQuery(...)
{
..........
IEnumerable<Account> query = cmd.ExecuteQuery<Account>(); return query.ToList(); ...........
}

public
class Account { /// <summary> /// 編號 /// </summary> public int id { get; set; } /// <summary> /// 用戶編號 /// </summary> public int userId { get; set; } ......... }

覺得不麻煩嗎? 好吧,如果你的User類也要用這個方法呢? 你需要把這個ExecuteQuery()這個方法抽出來通用,那么這里的cmd.ExecuteQuery<Account>()中Account怎么處理呢,替換為  Object  ? 這是會報錯的...這個地方我還不知道怎么處理???求路過的童鞋看看有什么好的解決方法,

      我想應該不只有這一個dll,然后我就去網上去淘啊,淘啊,淘...O(∩_∩)O哈哈~ 

      讓我淘到了:Community.CsharpSqlite.SqlLiteClient.WP7.dll, Community.CsharpSqlite.WP7.dll  ,神器啊....然后就杯具了...(最后提供下載)

      這倆dll提供了讀取數據的方法,但是不知道為什么,dll中的方法,在運行時方法名字變了..例如: read()-->reading(),太糾結了...還有其它一些問題就不細說了.

      可能我下載的dll是被人家修改過的,如果哪位有更好的,求分享!!!,或者有解決方法也行...

最后木有辦法,只好繼續使用  Community.CsharpSqlite.WP.dll 先提一個,也是不知道為什么,有些漢字輸入會報錯,例如,你輸入'大米' 程序會報'大'引發異常...

第二部分:  記賬本開發 

     1. 幫助類: SQLiteHelper  

       (1)  設置連接字符串:

             public static SQLiteConnection myDB = null;

             private static string fileName = "AccountData.DB";

            //fileName="Version=3,uri=file:AccountData.sqlite";-->這個是Community.CsharpSqlite.SqlLiteClient.WP7.dll定義數據庫文件的方式

      (2)  創建數據庫:

             打開數據庫,如果數據庫不存在就創建這個數據,-->這個是自動的,

             問題來了: 如果數據庫不存在,直接創建數據庫,順便創建表:(表Account),如果數據庫存在,就不能再創建表了啊,但是這個打開和創建數據庫是自動的

的樓主直接在SQL語句中寫" create table if not exists Account(....",  可以在這里判斷一下表存在與否 TabbleIsExist()

SELECT COUNT(*) FROM sqlite_master where type='table' and name='Account'

                        表Account不存在我才創建;

              之前看到過創建數據庫表自增字段的方式,發現好多都是錯誤的,正確的方式如下,並且表只能有一個主鍵.至少SQLite中是這樣:

CREATE TABLE Account(

             [id] INTEGER PRIMARY KEY AUTOINCREMENT,  --主鍵,自增

             [userId] INTEGER NOT NULL ,

             [itemID]INTEGER ,

             [item] nvarchar NOT NULL ,  --數據類型大小寫木有區別,但是大小寫統一比較好

             [cost] INTEGER ,

             [costTime] datetime ,  --大小寫木有區別

             [mark] int NOT NULL   --使用int也是可以的

) ;

       (3)  ExecuteNonQuery()方法: 這個沒有什么說的,很簡單,后面的代碼中都有...

   (4)  GetListAccount()方法: 是我要說的重點,弄這個太糾結了....

                 我們知道,WP7不支持DataTable,也木有其它的什么好東東可以承載數據,怎么辦,只好直接使用 Account類來接收數據,

                 返回一個List<Account>,這樣數據就出來了..

                   IEnumerable<Account> query = cmd.ExecuteQuery<Account>();

                   return query.ToList();

               悲劇的很...以后凡是涉及到數據查詢,讀取數據的都只能在這個方法上面折騰了...也是因為如此,我才花費N多時間折騰其它方式,

               木有辦法最后還是回到了這里...哎呦...

              以下是幫助類具體代碼:

SQLiteHelper
 public class SQLiteHelper
    {
       
         /*
     *  數據庫名: AccountData.DB 
        建表:
        a用戶表: User
        id(編號)          int  pk  uq
        name(用戶名)      nvarchar
        CreateTime(時間)  datetime

        b消費表: Account
        id(編號)          int pk  uq
        userId(用戶編號)  int
        itemId(消費項編號)int uq
        item(消費項)      nvarchar
        cost(消費金額)    int
        costTime(消費時間)dateTime
        mark(標志位1 生活必須,2 奢侈享受) int
     */

        #region 構造函數
        public SQLiteHelper()
        {
        }  
        #endregion
      
        /// <summary>
        /// 連接字符串  需要修改
        /// </summary>
        public static SQLiteConnection myDB = null; 

        private static string fileName = "AccountData.DB";//"Version=3,uri=file:AccountData.sqlite";
        
        //這里先定數據庫,之后再修改為參數化...
        /// <summary>
        /// 創建數據庫
        /// </summary>
        public static void CreateDB()
        {
            if(myDB==null)
            {
                try
                {
                    //@1 使用open()方法打開數據庫,如果數據庫不存在就創建此數據庫
                    myDB = new SQLiteConnection(fileName);
                    myDB.Open();
                }
                catch (SQLiteException ex)
                {
                    MessageBox.Show("錯誤信息: " + ex);
                }
                //@2 創建表(方法內部要判斷表是否存在)
                CreateTable();
                return;
            }
            myDB.Open();
        }

        /// <summary>
        /// 創建數據表 
        /// </summary>
        private static void CreateTable()
        {
            string strSql = string.Empty;
            if(myDB!=null)
            {
                try
                {
                    //先判斷表是否存在  也可以直接使用SQL語句
                    //create table if not exists tableword (id integer primary key AUTOINCREMENT, word text, desc blob)
                    //if (!TabbleIsExist("User"))
                    //{
                    //    strSql = "CREATE TABLE User ([id] INTEGER PRIMARY KEY AUTOINCREMENT,[name] nvarchar ,[createTime] datetime);"; 
                    //}

                    if (!TabbleIsExist("Account"))
                    {
                        strSql +=
                        "CREATE TABLE Account([id] INTEGER PRIMARY KEY AUTOINCREMENT,[userId] INTEGER NOT NULL ,[itemID]INTEGER ,[item] nvarchar NOT NULL ,[cost] INTEGER ,[costTime] datetime ,[mark] int NOT NULL) ;";
                    }
                    if(!string.IsNullOrEmpty(strSql))
                    {
                        int i = ExecuteNonQuery(strSql);
                    }
                }
                catch (SQLiteException ex)
                {
                    MessageBox.Show("錯誤信息: "+ex.Message);
                }
            }

        }
     
        /// <summary>
        /// 判斷數據庫中表是否存在
        /// </summary>
        /// <param name="tableName">表名,區分大小寫</param>
        /// <returns></returns>
        private static bool TabbleIsExist(String tableName)
        {
            if(string.IsNullOrEmpty(tableName))
            {
                return false;
            }
            if(myDB!=null)
            {
                string strSql = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + tableName + "'";
                SQLiteCommand cmd = myDB.CreateCommand(strSql);                
                if (Convert.ToInt32(cmd.ExecuteScalar()) >0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 執行SQL語句 添加,修改,刪除操作. 
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string strSql)
        {
            if (myDB != null)
            {
                try
                {
                    SQLiteCommand cmd = myDB.CreateCommand(strSql);
                    return cmd.ExecuteNonQuery();
                }
                catch (SQLiteException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return 0;
        }

        /// <summary>
        /// 執行SQL語句  查詢Account 專用
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static List<Account> GetListAccount(string strSql)
        {
            if(myDB!=null)
            {
                try
                {
                    SQLiteCommand cmd = myDB.CreateCommand(strSql);
                    IEnumerable<Account> query = cmd.ExecuteQuery<Account>();
                    return query.ToList();
                }
                catch (SQLiteException ex)
                {
                    MessageBox.Show("錯誤消息: " + ex);    
                }
            }
            return null;
        }     
    }

     幫助類搞定了,其它的就是小case了: 下面就只提供截圖了,具體實現簡單得很,就不獻丑了...

     2. 主界面:                                        3. 生活必須:                                      4. 奢侈享受:

      

           

      5. 詳情頁: 

          .............................

            就這么多吧,其它的就不提供了. 

 第三部分: 相關dll 和一個SQLite工具下載:

      下載地址: http://115.com/file/anlgefdc

 

        

 

 本文參考DBFocus的博客   地址: http://www.cnblogs.com/dbfocus/archive/2011/02/27/1966203.html


免責聲明!

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



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