unity3d在android使用sqlite

Shut Up and Show Them the Code.

using UnityEngine;using System;using System.Collections;using Mono.Data.Sqlite;using System.IO;public class DbAccess{ private SqliteConnection dbConnection;//sql連接 private SqliteCommand dbCommand = null;//sql命令 private SqliteDataReader dbReader;//sql讀取器 public DbAccess(string connectionString) { string appDBPath = ""; if (Application.platform == RuntimePlatform.WindowsEditor)//如果是windows編輯器中 { appDBPath = Application.dataPath + "/" + connectionString; } else if (Application.platform == RuntimePlatform.Android)// --如果是安卓平台 { appDBPath = Application.persistentDataPath + "/" + connectionString; if (!File.Exists(appDBPath) || fi.Length == 0) { var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + connectionString); // this is the path to your StreamingAssets in android while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldnt let this while loop unattended, place a timer and error check // then save to Application.persistentDataPath File.WriteAllBytes(appDBPath, loadDb.bytes); } } OpenDB("Data Source=" + appDBPath); } private void OpenDB(string connectionString) { try { dbConnection = new SqliteConnection(connectionString); dbConnection.Open(); Debug.Log("!!!!!! connect to db !!!!!!!!!!!!!"); } catch (System.Exception ex) { Debug.Log(ex.Message); } } public void CloseSqlConnection()//關閉資料庫連接 { if (dbCommand != null) dbCommand.Dispose(); dbCommand = null; if (dbReader != null) dbReader.Dispose(); dbReader = null; if (dbConnection != null) dbConnection.Close(); dbConnection = null; } public SqliteDataReader ExecuteQuery(string sqlQuery)//執行查詢 { dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = sqlQuery; dbReader = dbCommand.ExecuteReader(); return dbReader; } public int Query(string sql) { dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = sql; int result = 0; result = dbCommand.ExecuteNonQuery(); return result; }}

這個問題搞了2天,各種花式坑,又沒有官方提供文檔,真的是搞死個人。

主要問題在於安卓下的目錄讀寫許可權問題。

Step

1、添加庫文件到 項目AssetsPluginsAndroid 下

微雲分享

2、創建你的sqlite文件到 Assets 目錄下

3、隨意使用,隨意擴展。

我們的新浪微博↓

Sina Visitor Systemweibo.com

我們的官網↓

http://icaoguo.com

參考鏈接:

codecoding/SQLite4Unity3d

shreks7/SqliteForUnity

推薦閱讀:

兩個平均年齡十一歲的小男孩,做了兩款遊戲
美國玩家們是怎麼看待DLC和微交易的
遊戲資源傳送門

TAG:Unity遊戲引擎 | 遊戲開發 | SQLite |