初入江湖
- 麒麟币
- 38 枚
- 任务币
- 0 枚
- 威望
- 0 点
- 贡献
- 0 点
- 主题
- 9贴
- 在线时间
- 3 小时
|
以前在开发中一直使用IOS源生的数据库,通过传递消息的形式在与Unity3D中进行交互。本文我在详细说说如何使用C#语言来在MAC 操作系统下创建Unity本地数据库,我是C#控.
首先你需要得到Mono.Data.Sqlite.dll 文件 与System.Data.dll文件。如果你在Mac 操作系统下使用Unity那么很悲剧,找不到这两个文件,至少我没能找到。后来我在Windows下的Unity安装路径中找到了它。为了方便大家我将这两个文件上传至网盘中,如果没有这两个文件的朋友请下载。Unity数据库文件.zip
.zip文件下载完毕后直接解压,然后将Mono.Data.Sqlite.dll 文件 与System.Data.dll文件放在Unity工程中的Assets文件夹中。如下图所示,两个文件已经放置在Project视图当中。
Ok ,我们编写C#脚本,原始文章没有Unity数据库更新与删除的方法,我在这里加上更新与删除的方法,方便大家开发时使用。因为其实Unity中更新与删除数据库也是个比较重要的功能。
注意:下面脚本不要绑定在任何游戏对象身上,大家无需把它当作脚本可以当作一个工具类来使用。
[代码]java代码:
001using UnityEngine;
002
003using System;
004using System.Collections;
005using Mono.Data.Sqlite;
006
007public 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 }
|
评分
-
查看全部评分
|