Unity3D教程:与Sqlite数据库直连

开发 游戏开发
本文将为您介绍Unity 3D如何与Sqlite数据进行连接的过程,操作环境为Windows 7下。

环境介绍:

Windows7,Unity3D,SQLite Expert Personal 3

开发语言:

JavaScript

需要的dll文件:

Mono.Data.Sqlite.dll和sqlite3.dll,dll文件位置,截图:

Unity3D教程:Unity3D与Sqlite数据库直连

Unity3D教程:Unity3D与Sqlite数据库直连

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

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

Unity3D教程:Unity3D与Sqlite数据库直连

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

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

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

代码描述

*本代码是为了在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的等级改为.NET 2.0;那么这些操作做完了以后,如果你的代码写得没有问题,那么你就可以成功了。

细解释代码: 

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

7、如何在Unity3D中使用这个数据库的代码:

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

 

  运行结果:

Unity3D教程:Unity3D与Sqlite数据库直连

这是在Unity3D中运行的结果,数据的操作结果如下:

Unity3D教程:Unity3D与Sqlite数据库直连

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

Unity3D教程:Unity3D与Sqlite数据库直连

 

Unity3D教程:Unity3D与Sqlite数据库直连

文件当中数据:经测试,我们在对数据库中的数据进行操作的时候,我们的Unity3D中的数据也会发生相应的改变了!

原文链接:http://bbs.9ria.com/forum.php?mod=viewthread&tid=168629&fromuid=308561

 

 

责任编辑:彭凡 来源: 9RIA天地会
相关推荐

2013-04-25 09:56:24

unity3D手机游戏引擎

2013-04-25 10:03:07

unity3D手机游戏引擎

2013-06-19 08:52:48

Unity3D

2013-06-17 09:12:31

Unity3D

2013-06-18 08:49:15

2013-04-25 13:27:11

unity3D手机游戏引擎

2012-12-24 09:14:31

ios

2013-04-25 09:08:39

unity3D手机游戏引擎

2013-04-09 13:42:23

Unity3D基础知识梳理

2012-12-24 09:20:48

AndoidUnity3D

2012-12-24 09:09:27

AndoidUnity3D

2012-03-06 09:50:24

Android SQLAndroidSQLite3

2012-12-24 08:52:44

iOSUnity3D

2012-12-24 09:15:57

iOSUnity3D

2013-04-10 14:21:35

2012-12-24 09:19:31

iOSUnity3D

2018-07-13 09:20:30

SQLite数据库存储

2012-12-24 08:40:12

2012-12-24 09:08:14

iOSUnity3D

2012-12-24 08:51:23

iOSUnity3D
点赞
收藏

51CTO技术栈公众号