Unity3D研究院之在Unity中打开第三方数据库配合Android开发(三十二)

http://www.xuanyusong.com/archives/831


http://www.xuanyusong.com/archives/1454

如果大家对Unity中如何使用数据库还不是很了解那么请看我之前的这篇文章。Unity3D研究院之使用C#语言建立本地数据库(二十三)本篇文章我们讨论如何在Unity中打开一个第三方数据库配合Android与编辑器进行同步开发。如下图所示,这个是我目前工程的结构,为了方便调试MOMO使用预定义标签将编辑器与Android平台区分开,方便编辑器与Android平台同时调试。

下图如果看的不清楚,点击图片可查看大图。 不仅在Unity编辑器中可以显示数据库读取的内容,直接编译在真机中也可以显示数据库读取的内容。

 

按照上图所示我们把第三方数据库放在Plugins->Android->assets中,切记必须放在这里,否无无效,然后是代码。这个第三方数据库是MOMO以前做测试一个号码归属地的时候制作的。所以数据库的内容还是比较大的,蛤蛤。

DbAccess.cs

001 using UnityEngine;
002  
003 using System;
004 using System.Collections;
005 using Mono.Data.Sqlite;
006  
007 public class DbAccess
008  
009 {
010  
011     private SqliteConnection dbConnection;
012  
013     private SqliteCommand dbCommand;
014  
015     private SqliteDataReader reader;
016  
017     public DbAccess (string connectionString)
018  
019     {
020  
021         OpenDB (connectionString);
022  
023     }
024     public DbAccess ()
025     {
026  
027     }
028  
029     public void OpenDB (string connectionString)
030  
031     {
032         try
033          {
034             dbConnection = new SqliteConnection (connectionString);
035  
036             dbConnection.Open ();
037  
038             Debug.Log ("Connected to db");
039          }
040         catch(Exception e)
041         {
042             string temp1 = e.ToString();
043             Debug.Log(temp1);
044         }
045  
046     }
047  
048     public void CloseSqlConnection ()
049  
050     {
051  
052         if (dbCommand != null) {
053  
054             dbCommand.Dispose ();
055  
056         }
057  
058         dbCommand = null;
059  
060         if (reader != null) {
061  
062             reader.Dispose ();
063  
064         }
065  
066         reader = null;
067  
068         if (dbConnection != null) {
069  
070             dbConnection.Close ();
071  
072         }
073  
074         dbConnection = null;
075  
076         Debug.Log ("Disconnected from db.");
077  
078     }
079  
080     public SqliteDataReader ExecuteQuery (string sqlQuery)
081  
082     {
083  
084         dbCommand = dbConnection.CreateCommand ();
085  
086         dbCommand.CommandText = sqlQuery;
087  
088         reader = dbCommand.ExecuteReader ();
089  
090         return reader;
091  
092     }
093  
094     public SqliteDataReader ReadFullTable (string tableName)
095  
096     {
097  
098         string query = "SELECT * FROM " + tableName;
099  
100         return ExecuteQuery (query);
101  
102     }
103  
104     public SqliteDataReader InsertInto (string tableName, string[] values)
105  
106     {
107  
108         string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
109  
110         for (int i = 1; i < values.Length; ++i) {
111  
112             query += ", " + values[i];
113  
114         }
115  
116         query += ")";
117  
118         return ExecuteQuery (query);
119  
120     }
121  
122     public SqliteDataReader UpdateInto (string tableName, string []cols,string []colsvalues,string selectkey,string selectvalue)
123     {
124  
125         string query = "UPDATE "+tableName+" SET "+cols[0]+" = "+colsvalues[0];
126  
127         for (int i = 1; i < colsvalues.Length; ++i) {
128  
129              query += ", " +cols[i]+" ="+ colsvalues[i];
130         }
131  
132          query += " WHERE "+selectkey+" = "+selectvalue+" ";
133  
134         return ExecuteQuery (query);
135     }
136  
137     public SqliteDataReader Delete(string tableName,string []cols,string []colsvalues)
138     {
139             string query = "DELETE FROM "+tableName + " WHERE " +cols[0] +" = " + colsvalues[0];
140  
141             for (int i = 1; i < colsvalues.Length; ++i) {
142  
143                 query += " or " +cols[i]+" = "+ colsvalues[i];
144             }
145         Debug.Log(query);
146         return ExecuteQuery (query);
147     }
148  
149     public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)
150  
151     {
152  
153         if (cols.Length != values.Length) {
154  
155             throw new SqliteException ("columns.Length != values.Length");
156  
157         }
158  
159         string query = "INSERT INTO " + tableName + "(" + cols[0];
160  
161         for (int i = 1; i < cols.Length; ++i) {
162  
163             query += ", " + cols[i];
164  
165         }
166  
167         query += ") VALUES (" + values[0];
168  
169         for (int i = 1; i < values.Length; ++i) {
170  
171             query += ", " + values[i];
172  
173         }
174  
175         query += ")";
176  
177         return ExecuteQuery (query);
178  
179     }
180  
181     public SqliteDataReader DeleteContents (string tableName)
182  
183     {
184  
185         string query = "DELETE FROM " + tableName;
186  
187         return ExecuteQuery (query);
188  
189     }
190  
191     public SqliteDataReader CreateTable (string name, string[] col, string[] colType)
192  
193     {
194  
195         if (col.Length != colType.Length) {
196  
197             throw new SqliteException ("columns.Length != colType.Length");
198  
199         }
200  
201         string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
202  
203         for (int i = 1; i < col.Length; ++i) {
204  
205             query += ", " + col[i] + " " + colType[i];
206  
207         }
208  
209         query += ")";
210  
211         return ExecuteQuery (query);
212  
213     }
214  
215     public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)
216  
217     {
218  
219         if (col.Length != operation.Length || operation.Length != values.Length) {
220  
221             throw new SqliteException ("col.Length != operation.Length != values.Length");
222  
223         }
224  
225         string query = "SELECT " + items[0];
226  
227         for (int i = 1; i < items.Length; ++i) {
228  
229             query += ", " + items[i];
230  
231         }
232  
233         query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
234  
235         for (int i = 1; i < col.Length; ++i) {
236  
237             query += " AND " + col[i] + operation[i] + "'" + values[0] + "' ";
238  
239         }
240  
241         return ExecuteQuery (query);
242  
243     }
244  
245 }

 

然后是Test.cs直接把它挂在摄像机对象身上。

01 using UnityEngine;
02 using System.Collections;
03 using System.Collections.Generic;
04 using System.IO;
05 using Mono.Data.Sqlite;
06 public class Test  :MonoBehaviour
07 {
08     //这三个是从数据库中取得的字段内容
09     string  number = "null";
10     string  city= "null";
11     string  location = "null";
12  
13     //处理在Android中显示中文
14     public GUISkin skin;
15  
16     void Start ()
17     {
18  
19         loadSQL ();
20     }
21  
22     void loadSQL ()
23     {
24  
25 //如果运行在编辑器中
26 #if UNITY_EDITOR
27             //通过路径找到第三方数据库
28             string appDBPath = Application.dataPath + "/Plugins/Android/assets/" "location.db";
29             DbAccess db = new DbAccess("URI=file:" + appDBPath);
30 //如果运行在Android设备中
31 #elif UNITY_ANDROID
32  
33         //将第三方数据库拷贝至Android可找到的地方
34         string appDBPath = Application.persistentDataPath + "/" "location.db";
35  
36         //如果已知路径没有地方放数据库,那么我们从Unity中拷贝
37         if(!File.Exists(appDBPath))
38  
39         {
40             //用www先从Unity中下载到数据库
41             WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" "location.db");
42  
43             //拷贝至规定的地方
44             File.WriteAllBytes(appDBPath, loadDB.bytes);
45  
46         }
47  
48         //在这里重新得到db对象。
49         DbAccess db = new DbAccess("URI=file:" + appDBPath);
50  
51 #endif 
52  
53         using (SqliteDataReader sqReader = db.SelectWhere("location_date",new string[]{"number","city","location"},new string[]{"_id"},newstring[]{"="},new string[]{"25"}))
54         {
55  
56             while (sqReader.Read())
57             {
58                   //从数据库中找到对应字段
59                   number =  sqReader.GetString(sqReader.GetOrdinal("number"));
60                   city =  sqReader.GetString(sqReader.GetOrdinal("city"));
61                   location = sqReader.GetString(sqReader.GetOrdinal("location")) ;         
62  
63                 Debug.Log("number =" + number + " city =" + city + " location =" + location );
64  
65             }
66  
67             sqReader.Close();
68         }
69  
70         db.CloseSqlConnection();
71  
72     }
73  
74     void OnGUI()
75     {
76          GUI.skin = skin;
77  
78             GUILayout.Box("number =" + number);
79             GUILayout.Box("city =" + city);
80             GUILayout.Box("location =" + location);
81     }
82  
83 }

 

上面代码中我们使用到了预定于标签,用于编译时区分游戏平台与版本。这么一来我们既可以在编辑器中操作数据库也可以在Android中操作数据库一举两得,主要是是Android平台比较特殊,不能从Unity的Assets资源路径中读取二进制文件。说道二进制文件,这里不仅读取第三方数据库还可以读取其它文件,二进制文件都可以读取,比如文本文件、图片、资源等等。

需要注意的是你得把你的二进制文件放在Plugins->Android->assets中,然后根据下面的路径就可以在Android中读取。

string Path  = jar:file://” + Application.dataPath + “!/assets/” + “你的文件“;

 

另外,使用这种方法读取地方放数据库后,是可以继续向数据库执行插入、删除、修改 、查询、等操作,用起来还是比较方便的。

 

Unity预定义标签的种类还有很多,不仅可以区分平台还可以区分版本。

  
UNITY_EDITORDefine for calling Unity Editor scripts from your game code.
UNITY_STANDALONE_OSXPlatform define for compiling/executing code specifically for Mac OS (This includes Universal, PPC and Intel architectures).
UNITY_DASHBOARD_WIDGETPlatform define when creating code for Mac OS dashboard widgets.
UNITY_STANDALONE_WINUse this when you want to compile/execute code for Windows stand alone applications.
UNITY_WEBPLAYERPlatform define for web player content (this includes Windows and Mac Web player executables).
UNITY_WIIPlatform define for compiling/executing code for the Wii console.
UNITY_IPHONEPlatform define for compiling/executing code for the iPhone platform.
UNITY_ANDROIDPlatform define for the Android platform.
UNITY_PS3Platform define for running PlayStation 3 code.
UNITY_XBOX360Platform define for executing Xbox 360 code.
UNITY_NACLPlatform define when compiling code for Google native client (this will be set additionally to UNITY_WEBPLAYER).
UNITY_FLASHPlatform define when compiling code for Adobe Flash.

Note: These defines were introduced at version 3.0.

Also you can compile code selectively depending on the version of the engine you are working on. Currently the supported ones are:

UNITY_2_6Platform define for the major version of Unity 2.6.
UNITY_2_6_1Platform define for specific version 1 from the major release 2.6.
UNITY_3_0Platform define for the major version of Unity 3.0.
UNITY_3_0_0Platform define for the specific version 0 of Unity 3.0.
UNITY_3_1Platform define for major version of Unity 3.1.
UNITY_3_2Platform define for major version of Unity 3.2.
UNITY_3_3Platform define for major version of Unity 3.3.
UNITY_3_4Platform define for major version of Unity 3.4.
UNITY_3_5Platform define for major version of Unity 3.5. 

 详细内容可以查看官网http://docs.unity3d.com/Documentation/Manual/PlatformDependentCompilation.html

用法就不解释了,地球人都知道。

雨松MOMO希望和大家一起进步,加油~~~最后文本的源码下载:http://vdisk.weibo.com/s/ac3xI


StreamingAssets 是一个只读的文件夹, 把二进制文件可以提前放在这里面!


yx8728

4.1.2测试失败,后把db放到StreamingAssets下面搞定



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值