如何与Sqlite数据库进行直连的问题。不废话了,直接介绍吧。原文来自于:http://wiki.unity3d.com/index.php/Sqlite,大家可以去学习下。

1、环境介绍:

,Unity3D,SQLite Expert Personal 3

2、开发语言:

JavaScript

dll文件:

和sqlite3.dll,稍后我会将所有文件打包在一起供大家讨论下,先看下这些dll文件应该被放在哪里,看下面的截图:


,一定要在这个目录下,请跟我保持一致。

4、如果需要将编译好的程序发布成功的话,需要改一些地方,具体见下面的截图:



要改动的地方我已经用红色标记出来了,注意这个要改成.NET2.0 ,这样才能够发布的。系统默认的不是 .NET2.0 ,大家这一点要注意!!!

5、下面来看下代码吧,先看下如何创建数据库的代码,这一篇代码是不用挂到任何对象上面去的,你只用把它当成一个工具即可。如下所示:

/*  Javascript class for accessing SQLite objects.  
      To use it, you need to make sure you COPY Mono.Data.SQLiteClient.dll from wherever it lives in your Unity directory
      to your project's Assets folder
      Originally created by dklompmaker in 2009
      http://forum.unity3d.com/threads ... sier-Database-Stuff   
      Modified 2011 by Alan Chatham           */
 //#pragma strict

代码描述

本代码是为了在Windows环境下运行unity3d和Sqlite数据库而写的;实现的基本功能是unity3d能够与数据库之间进行基本的通信,比如说

unity3d中得到的数据也会在刷新了之后跟着改变;这只是一个基本的核心的技术,为的是能够应用在大型的unity3d

        项目中,能够存储场景中的项目的属性,在需要改变对象的属性或增加、减少等对象时能够很方便的用得上。

dll文件,一个是Mono.Data.SQLiteClient.dll,另外一个是sqlite3.dll,这些文件都能够在unity3d的安装目录中找得到。

\Assets\Plugins\,没有Plugins文件夹就必须创建这个文件夹,然后将这两个dll文件放在该文件夹写。

PC上面发布成可执行文件,还需要改动一些地方。在unity3d中的Play Setting ->Other Setting 中将Api Compatibility的等级改为

那么这些操作做完了以后,如果你的代码写得没有问题,那么你就可以成功了。

        好了,下面咱们来详细解释下代码吧。


1. *
2.  */
3.  import          System.Data;  // we import our  data class 我们先导入我们的数据集
4.  import          Mono.Data.Sqlite; // we import sqlite        我们导入sqlite数据集,也就是Plugins文件夹下的那个dll文件
5.  
6.  class dbAccess {
7.      // variables for basic query access
8.      private var connection : String;        //数据库的连接字符串,用于建立与特定数据源的连接
9.      private var dbcon : IDbConnection;        //IDbConnection的连接对象,其实就是一个类对象
10.      private var dbcmd : IDbCommand;                //IDbCommand类对象,用来实现操作数据库的命令:注解:我在网上资料看到的如何实现对数据库执行命令:
11.                                                                              //首先创建一个IDbConnection连接对象,然后将一条数据库命令赋值给一个字符串,利用这个字符串和连接对象
12.                                                                              //就可以创建(new)一个IDbCommand对象了,然后使用提供的方法就可以执行这个命令了。
13.      private var reader : IDataReader;        //reader的作用就是读取结果集的一个或多个只进结果流
14.  
15.      function OpenDB(p : String){
16.      connection = "URI=file:" + p; // we set the connection to our database
17.      dbcon = new SqliteConnection(connection);
18.      dbcon.Open();                                                //打开数据库连接操作
19.      }
20.  
21.      function BasicQuery(q : String, r : boolean){ // run a baic Sqlite query
22.          dbcmd = dbcon.CreateCommand(); // create empty command
23.          dbcmd.CommandText = q; // fill the command
24.          reader = dbcmd.ExecuteReader(); // execute command which returns a reader  返回IDataReader的对象,创建IDataReader的对象
25.          if(r){ // if we want to return the reader
26.          return reader; // return the reader        返回读取的对象,就是读到了什么东西
27.          }
28.      }
29.  
30.      // This returns a 2 dimensional ArrayList with all the
31.      //  data from the table requested
32.      function ReadFullTable(tableName : String){
33.          var query : String;
34.          query = "SELECT * FROM " + tableName;        
35.          dbcmd = dbcon.CreateCommand();
36.          dbcmd.CommandText = query;
37.          reader = dbcmd.ExecuteReader();
38.          var readArray = new ArrayList();
39.          while(reader.Read()){
40.              var lineArray = new ArrayList();
41.              for (var i = 0; i < reader.FieldCount; i++)
42.                  lineArray.Add(reader.GetValue(i)); // This reads the entries in a row
43.              readArray.Add(lineArray); // This makes an array of all the rows
44.          }
45.          return readArray; // return matches
46.      }
47.  
48.      // This function deletes all the data in the given table.  Forever.  WATCH OUT! Use sparingly, if at all
49.      function DeleteTableContents(tableName : String){
50.      var query : String;
51.      query = "DELETE FROM " + tableName;
52.      dbcmd = dbcon.CreateCommand();
53.      dbcmd.CommandText = query;
54.      reader = dbcmd.ExecuteReader();
55.      }
56.  
57.      function CreateTable(name : String, col : Array, colType : Array){ // Create a table, name, column array, column type array
58.          var query : String;
59.          query  = "CREATE TABLE " + name + "(" + col[0] + " " + colType[0];
60.          for(var i=1; i<col.length; i++){
61.              query += ", " + col + " " + colType;
62.          }
63.          query += ")";
64.          dbcmd = dbcon.CreateCommand(); // create empty command
65.          dbcmd.CommandText = query; // fill the command
66.          reader = dbcmd.ExecuteReader(); // execute command which returns a reader
67.      }
68.      function InsertIntoSingle(tableName : String, colName : String, value : String){ // single insert
69.          var query : String;
70.          query = "INSERT INTO " + tableName + "(" + colName + ") " + "VALUES (" + value + ")";
71.          dbcmd = dbcon.CreateCommand(); // create empty command
72.          dbcmd.CommandText = query; // fill the command
73.          reader = dbcmd.ExecuteReader(); // execute command which returns a reader
74.      }
75.      function InsertIntoSpecific(tableName : String, col : Array, values : Array){ // Specific insert with col and values
76.          var query : String;
77.          query = "INSERT INTO " + tableName + "(" + col[0];
78.          for(var i=1; i<col.length; i++){
79.              query += ", " + col;
80.          }
81.          query += ") VALUES (" + values[0];
82.          for(i=1; i<values.length; i++){
83.              query += ", " + values;
84.          }
85.          query += ")";
86.          dbcmd = dbcon.CreateCommand();
87.          dbcmd.CommandText = query;
88.          reader = dbcmd.ExecuteReader();
89.      }
90.  
91.      function InsertInto(tableName : String, values : Array){ // basic Insert with just values
92.          var query : String;
93.          query = "INSERT INTO " + tableName + " VALUES (" + values[0];
94.          for(var i=1; i<values.length; i++){
95.              query += ", " + values;
96.          }
97.          query += ")";
98.          dbcmd = dbcon.CreateCommand();
99.          dbcmd.CommandText = query;
100.          reader = dbcmd.ExecuteReader();
101.      }
102.  
103.      // This function reads a single column
104.      //  wCol is the WHERE column, wPar is the operator you want to use to compare with,
105.      //  and wValue is the value you want to compare against.
106.      //  Ex. - SingleSelectWhere("puppies", "breed", "earType", "=", "floppy")
107.      //  returns an array of matches from the command: SELECT breed FROM puppies WHERE earType = floppy;
108.      function SingleSelectWhere(tableName : String, itemToSelect : String, wCol : String, wPar : String, wValue : String){ // Selects a single Item
109.          var query : String;
110.          query = "SELECT " + itemToSelect + " FROM " + tableName + " WHERE " + wCol + wPar + wValue;        
111.          dbcmd = dbcon.CreateCommand();
112.          dbcmd.CommandText = query;
113.          reader = dbcmd.ExecuteReader();
114.          var readArray = new Array();
115.          while(reader.Read()){
116.              readArray.Push(reader.GetString(0)); // Fill array with all matches
117.          }
118.          return readArray; // return matches
119.      }
120.  
121.  
122.      function CloseDB(){
123.          reader.Close(); // clean everything up
124.          reader = null;
125.          dbcmd.Dispose();
126.          dbcmd = null;
127.          dbcon.Close();
128.          dbcon = null;
129.      }
130.  
131.  }


复制代码


上述代码的基本的增删改查什么的都具有了,仔细看看然后加上我的注释,这段代码也不难,就是可能初学的话有点难以接受,说实话我也是初学,如果没有原文,我是绝对写不出来这个的。。。

7、好了,下面我们再来看看如何在Unity3D中使用这个数据库的代码吧:


1.  //#pragma strict
2.  /*  Script for testing out SQLite in Javascript
3.            2011 - Alan Chatham
4.            Released into the public domain
5.  
6.          This script is a GUI script - attach it to your main camera.
7.          It creates/opens a SQLite database, and with the GUI you can read and write to it.
8.                                          */
9.  
10.  // This is the file path of the database file we want to use
11.  // Right now, it'll load TestDB.sqdb in the project's root folder.
12.  // If one doesn't exist, it will be automatically created.
13.  public var DatabaseName : String = "TestDB.sqdb";
14.  
15.  // This is the name of the table we want to use
16.  public var TableName : String = "TestTable";
17.  var db : dbAccess;
18.  
19.  function Start(){
20.      // Give ourselves a dbAccess object to work with, and open it
21.  
22.  
23.  
24.      db = new dbAccess();
25.      db.OpenDB(DatabaseName);
26.      // Let's make sure we've got a table to work with as well!
27.      var tableName = TableName;
28.      var columnNames = new Array("firstName","lastName");
29.      var columnValues = new Array("text","text");
30.      try {db.CreateTable(tableName,columnNames,columnValues);
31.      }
32.      catch(e){// Do nothing - our table was already created判断表是否被创建了
33.          //- we don't care about the error, we just don't want to see it
34.      }
35.  }
36.  
37.  // These variables just hold info to display in our GUI
38.  var firstName : String = "First Name";
39.  var lastName : String = "Last Name";
40.  var DatabaseEntryStringWidth = 100;
41.  var scrollPosition : Vector2;
42.  var databaseData : ArrayList = new ArrayList();
43.  
44.  // This GUI provides us with a way to enter data into our database
45.  //  as well as a way to view it
46.  function OnGUI(){
47.      GUI.Box(Rect (25,25,Screen.width - 50, Screen.height - 50),"Data");
48.      GUILayout.BeginArea(Rect(50, 50, Screen.width - 100, Screen.height - 100));
49.      // This first block allows us to enter new entries into our table
50.          GUILayout.BeginHorizontal();
51.              firstName = GUILayout.TextField(firstName, GUILayout.Width (DatabaseEntryStringWidth));
52.              lastName = GUILayout.TextField(lastName, GUILayout.Width (DatabaseEntryStringWidth));
53.  
54.              //lastName = GUILayout.TextField();
55.          GUILayout.EndHorizontal();
56.  
57.          if (GUILayout.Button("Add to database")){
58.              // Insert the data
59.              InsertRow(firstName,lastName);
60.              // And update the readout of the database
61.              databaseData = ReadFullTable();
62.          }
63.          // This second block gives us a button that will display/refresh the contents of our database
64.          GUILayout.BeginHorizontal();
65.              if (GUILayout.Button ("Read Database"))        
66.                  databaseData = ReadFullTable();
67.              if (GUILayout.Button("Clear"))
68.                  databaseData.Clear();
69.          GUILayout.EndHorizontal();
70.  
71.          GUILayout.Label("Database Contents");
72.          scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(100));
73.              for (var line : ArrayList in databaseData){
74.                  GUILayout.BeginHorizontal();
75.                  for (var s in line){
76.                      GUILayout.Label(s.ToString(), GUILayout.Width(DatabaseEntryStringWidth));
77.                  }
78.                  GUILayout.EndHorizontal();
79.              }
80.  
81.          GUILayout.EndScrollView();
82.          if (GUILayout.Button("Delete All Data")){ Unity3D与Sqlite数据库直连.rar (168.27 KB, 下载次数: 239) 
83.  
84.  
85. Unity3D与Sqlite数据库直连.rar (446.06 KB, 下载次数: 584) 
86.  
87.  
88.  
89.  
90.  
91.              DeleteTableContents();
92.              databaseData = ReadFullTable();
93.          }
94.      GUILayout.EndArea();
95.  }
96.  
97.  // Wrapper function for inserting our specific entries into our specific database and table for this file
98.  function InsertRow(firstName, lastName){
99.      var values = new Array(("'"+firstName+"'"),("'"+lastName+"'"));
100.      db.InsertInto(TableName, values);
101.  }
102.  
103.  // Wrapper function, so we only mess with our table.
104.  function ReadFullTable(){
105.      return db.ReadFullTable(TableName);
106.  }
107.  
108.  // Another wrapper function...
109.  function DeleteTableContents(){
110.      db.DeleteTableContents(TableName);
111.  }


复制代码


这一段代码是要你挂在你的主摄像机上面的,其实我对数据库方面的知识很浅陋,很多地方还不是很理解,希望有高人能够将这段代码进行详细的注释,以便能让我们这种菜鸟级别的能够充分吸收啊。。。

9、下面咱们再来看看我们的运行结果吧:



这是在Unity3D中运行的结果,我们试试对数据的操作会怎么样



我们看见了我们对数据的操作能够成功,经过测试,其他的Button也都能出现相对应的效果,那我们再看看这个到底有没有生成我们想要的数据库文件:

看看截图大家就知道了: 


看见没,生成了我们想要的数据库文件了。那我们再来看看这个文件当中有木有数据:




  1. 看见了没,我们成功了。经过测试,我们在对数据库中的数据进行操作的时候,我们的Unity3D中的数据也会发生相应的改变了,所以,这次我们成功了。在这里我们要感谢原文的支持哈。希望路过的高手勿喷哈。。。


复制代码