首頁 資料庫 mysql教程 Unity3D与Sqlite数据库直连

Unity3D与Sqlite数据库直连

Jun 07, 2016 pm 03:30 PM
http sqlite unity3d 資料庫 直連 網址

网址:http://bbs.9ria.com/forum.php?mod=viewthreadtid=168629fromuid=308561 这几天也顺便研究了下Unity3D 如何与 Sqlite 数据库进行直连的问题。不废话了,直接介绍吧。原文来自于: http://wiki.unity3d.com/index.php/Sqlite ,大家可以去学习下。 1、

网址:http://bbs.9ria.com/forum.php?mod=viewthread&tid=168629&fromuid=308561

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

1、环境介绍:

Windows7Unity3DSQLite Expert Personal 3

2、开发语言:

JavaScript

3、需要的dll文件:

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

Unity3D与Sqlite数据库直连

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

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

Unity3D与Sqlite数据库直连

要改动的地方我已经用红色标记出来了,注意这个要改成.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环境下运行unity3dSqlite数据库而写的;实现的基本功能是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. */
  3. import          System.Data;  // we import our  data class 我们先导入我们的数据集
  4. import          Mono.Data.Sqlite; // we import sqlite        我们导入sqlite数据集,也就是Plugins文件夹下的那个dll文件

  5. class dbAccess {
  6.     // variables for basic query access
  7.     private var connection : String;        //数据库的连接字符串,用于建立与特定数据源的连接
  8.     private var dbcon : IDbConnection;        //IDbConnection的连接对象,其实就是一个类对象
  9.     private var dbcmd : IDbCommand;                //IDbCommand类对象,用来实现操作数据库的命令:注解:我在网上资料看到的如何实现对数据库执行命令:
  10.                                                                             //首先创建一个IDbConnection连接对象,然后将一条数据库命令赋值给一个字符串,利用这个字符串和连接对象
  11.                                                                             //就可以创建(new)一个IDbCommand对象了,然后使用提供的方法就可以执行这个命令了。
  12.     private var reader : IDataReader;        //reader的作用就是读取结果集的一个或多个只进结果流

  13.     function OpenDB(p : String){
  14.     connection = "URI=file:" + p; // we set the connection to our database
  15.     dbcon = new SqliteConnection(connection);
  16.     dbcon.Open();                                                //打开数据库连接操作
  17.     }

  18.     function BasicQuery(q : String, r : boolean){ // run a baic Sqlite query
  19.         dbcmd = dbcon.CreateCommand(); // create empty command
  20.         dbcmd.CommandText = q; // fill the command
  21.         reader = dbcmd.ExecuteReader(); // execute command which returns a reader  返回IDataReader的对象,创建IDataReader的对象
  22.         if(r){ // if we want to return the reader
  23.         return reader; // return the reader        返回读取的对象,就是读到了什么东西
  24.         }
  25.     }

  26.     // This returns a 2 dimensional ArrayList with all the
  27.     //  data from the table requested
  28.     function ReadFullTable(tableName : String){
  29.         var query : String;
  30.         query = "SELECT * FROM " + tableName;        
  31.         dbcmd = dbcon.CreateCommand();
  32.         dbcmd.CommandText = query;
  33.         reader = dbcmd.ExecuteReader();
  34.         var readArray = new ArrayList();
  35.         while(reader.Read()){
  36.             var lineArray = new ArrayList();
  37.             for (var i = 0; i
  38.                 lineArray.Add(reader.GetValue(i)); // This reads the entries in a row
  39.             readArray.Add(lineArray); // This makes an array of all the rows
  40.         }
  41.         return readArray; // return matches
  42.     }

  43.     // This function deletes all the data in the given table.  Forever.  WATCH OUT! Use sparingly, if at all
  44.     function DeleteTableContents(tableName : String){
  45.     var query : String;
  46.     query = "DELETE FROM " + tableName;
  47.     dbcmd = dbcon.CreateCommand();
  48.     dbcmd.CommandText = query;
  49.     reader = dbcmd.ExecuteReader();
  50.     }

  51.     function CreateTable(name : String, col : Array, colType : Array){ // Create a table, name, column array, column type array
  52.         var query : String;
  53.         query  = "CREATE TABLE " + name + "(" + col[0] + " " + colType[0];
  54.         for(var i=1; i
  55.             query += ", " + col + " " + colType;
  56.         }
  57.         query += ")";
  58.         dbcmd = dbcon.CreateCommand(); // create empty command
  59.         dbcmd.CommandText = query; // fill the command
  60.         reader = dbcmd.ExecuteReader(); // execute command which returns a reader
  61.     }
  62.     function InsertIntoSingle(tableName : String, colName : String, value : String){ // single insert
  63.         var query : String;
  64.         query = "INSERT INTO " + tableName + "(" + colName + ") " + "VALUES (" + value + ")";
  65.         dbcmd = dbcon.CreateCommand(); // create empty command
  66.         dbcmd.CommandText = query; // fill the command
  67.         reader = dbcmd.ExecuteReader(); // execute command which returns a reader
  68.     }
  69.     function InsertIntoSpecific(tableName : String, col : Array, values : Array){ // Specific insert with col and values
  70.         var query : String;
  71.         query = "INSERT INTO " + tableName + "(" + col[0];
  72.         for(var i=1; i
  73.             query += ", " + col;
  74.         }
  75.         query += ") VALUES (" + values[0];
  76.         for(i=1; i
  77.             query += ", " + values;
  78.         }
  79.         query += ")";
  80.         dbcmd = dbcon.CreateCommand();
  81.         dbcmd.CommandText = query;
  82.         reader = dbcmd.ExecuteReader();
  83.     }

  84.     function InsertInto(tableName : String, values : Array){ // basic Insert with just values
  85.         var query : String;
  86.         query = "INSERT INTO " + tableName + " VALUES (" + values[0];
  87.         for(var i=1; i
  88.             query += ", " + values;
  89.         }
  90.         query += ")";
  91.         dbcmd = dbcon.CreateCommand();
  92.         dbcmd.CommandText = query;
  93.         reader = dbcmd.ExecuteReader();
  94.     }

  95.     // This function reads a single column
  96.     //  wCol is the WHERE column, wPar is the operator you want to use to compare with,
  97.     //  and wValue is the value you want to compare against.
  98.     //  Ex. - SingleSelectWhere("puppies", "breed", "earType", "=", "floppy")
  99.     //  returns an array of matches from the command: SELECT breed FROM puppies WHERE earType = floppy;
  100.     function SingleSelectWhere(tableName : String, itemToSelect : String, wCol : String, wPar : String, wValue : String){ // Selects a single Item
  101.         var query : String;
  102.         query = "SELECT " + itemToSelect + " FROM " + tableName + " WHERE " + wCol + wPar + wValue;        
  103.         dbcmd = dbcon.CreateCommand();
  104.         dbcmd.CommandText = query;
  105.         reader = dbcmd.ExecuteReader();
  106.         var readArray = new Array();
  107.         while(reader.Read()){
  108.             readArray.Push(reader.GetString(0)); // Fill array with all matches
  109.         }
  110.         return readArray; // return matches
  111.     }


  112.     function CloseDB(){
  113.         reader.Close(); // clean everything up
  114.         reader = null;
  115.         dbcmd.Dispose();
  116.         dbcmd = null;
  117.         dbcon.Close();
  118.         dbcon = null;
  119.     }

  120. }
复制代码

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

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.         It creates/opens a SQLite database, and with the GUI you can read and write to it.
  7.                                         */

  8. // This is the file path of the database file we want to use
  9. // Right now, it'll load TestDB.sqdb in the project's root folder.
  10. // If one doesn't exist, it will be automatically created.
  11. public var DatabaseName : String = "TestDB.sqdb";

  12. // This is the name of the table we want to use
  13. public var TableName : String = "TestTable";
  14. var db : dbAccess;

  15. function Start(){
  16.     // Give ourselves a dbAccess object to work with, and open it



  17.     db = new dbAccess();
  18.     db.OpenDB(DatabaseName);
  19.     // Let's make sure we've got a table to work with as well!
  20.     var tableName = TableName;
  21.     var columnNames = new Array("firstName","lastName");
  22.     var columnValues = new Array("text","text");
  23.     try {db.CreateTable(tableName,columnNames,columnValues);
  24.     }
  25.     catch(e){// Do nothing - our table was already created判断表是否被创建了
  26.         //- we don't care about the error, we just don't want to see it
  27.     }
  28. }

  29. // These variables just hold info to display in our GUI
  30. var firstName : String = "First Name";
  31. var lastName : String = "Last Name";
  32. var DatabaseEntryStringWidth = 100;
  33. var scrollPosition : Vector2;
  34. var databaseData : ArrayList = new ArrayList();

  35. // This GUI provides us with a way to enter data into our database
  36. //  as well as a way to view it
  37. function OnGUI(){
  38.     GUI.Box(Rect (25,25,Screen.width - 50, Screen.height - 50),"Data");
  39.     GUILayout.BeginArea(Rect(50, 50, Screen.width - 100, Screen.height - 100));
  40.     // This first block allows us to enter new entries into our table
  41.         GUILayout.BeginHorizontal();
  42.             firstName = GUILayout.TextField(firstName, GUILayout.Width (DatabaseEntryStringWidth));
  43.             lastName = GUILayout.TextField(lastName, GUILayout.Width (DatabaseEntryStringWidth));

  44.             //lastName = GUILayout.TextField();
  45.         GUILayout.EndHorizontal();

  46.         if (GUILayout.Button("Add to database")){
  47.             // Insert the data
  48.             InsertRow(firstName,lastName);
  49.             // And update the readout of the database
  50.             databaseData = ReadFullTable();
  51.         }
  52.         // This second block gives us a button that will display/refresh the contents of our database
  53.         GUILayout.BeginHorizontal();
  54.             if (GUILayout.Button ("Read Database"))        
  55.                 databaseData = ReadFullTable();
  56.             if (GUILayout.Button("Clear"))
  57.                 databaseData.Clear();
  58.         GUILayout.EndHorizontal();

  59.         GUILayout.Label("Database Contents");
  60.         scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(100));
  61.             for (var line : ArrayList in databaseData){
  62.                 GUILayout.BeginHorizontal();
  63.                 for (var s in line){
  64.                     GUILayout.Label(s.ToString(), GUILayout.Width(DatabaseEntryStringWidth));
  65.                 }
  66.                 GUILayout.EndHorizontal();
  67.             }

  68.         GUILayout.EndScrollView();
  69.         if (GUILayout.Button("Delete All Data")){ Unity3D与Sqlite数据库直连Unity3D与Sqlite数据库直连.rar (168.27 KB, 下载次数: 239) 


  70. Unity3D与Sqlite数据库直连 Unity3D与Sqlite数据库直连.rar (446.06 KB, 下载次数: 584) 





  71.             DeleteTableContents();
  72.             databaseData = ReadFullTable();
  73.         }
  74.     GUILayout.EndArea();
  75. }

  76. // Wrapper function for inserting our specific entries into our specific database and table for this file
  77. function InsertRow(firstName, lastName){
  78.     var values = new Array(("'"+firstName+"'"),("'"+lastName+"'"));
  79.     db.InsertInto(TableName, values);
  80. }

  81. // Wrapper function, so we only mess with our table.
  82. function ReadFullTable(){
  83.     return db.ReadFullTable(TableName);
  84. }

  85. // Another wrapper function...
  86. function DeleteTableContents(){
  87.     db.DeleteTableContents(TableName);
  88. }
复制代码

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

9、下面咱们再来看看我们的运行结果吧:Unity3D与Sqlite数据库直连

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

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

看看截图大家就知道了: Unity3D与Sqlite数据库直连

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

Unity3D与Sqlite数据库直连

  1. 看见了没,我们成功了。经过测试,我们在对数据库中的数据进行操作的时候,我们的Unity3D中的数据也会发生相应的改变了,所以,这次我们成功了。在这里我们要感谢原文的支持哈。希望路过的高手勿喷哈。。。
复制代码
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
iOS 18 新增「已復原」相簿功能 可找回遺失或損壞的照片 iOS 18 新增「已復原」相簿功能 可找回遺失或損壞的照片 Jul 18, 2024 am 05:48 AM

蘋果公司最新發布的iOS18、iPadOS18以及macOSSequoia系統為Photos應用程式增添了一項重要功能,旨在幫助用戶輕鬆恢復因各種原因遺失或損壞的照片和影片。這項新功能在Photos應用的"工具"部分引入了一個名為"已恢復"的相冊,當用戶設備中存在未納入其照片庫的圖片或影片時,該相冊將自動顯示。 "已恢復"相簿的出現為因資料庫損壞、相機應用未正確保存至照片庫或第三方應用管理照片庫時照片和視頻丟失提供了解決方案。使用者只需簡單幾步

如何在PHP中處理資料庫連線錯誤 如何在PHP中處理資料庫連線錯誤 Jun 05, 2024 pm 02:16 PM

PHP處理資料庫連線報錯,可以使用下列步驟:使用mysqli_connect_errno()取得錯誤代碼。使用mysqli_connect_error()取得錯誤訊息。透過擷取並記錄這些錯誤訊息,可以輕鬆識別並解決資料庫連接問題,確保應用程式的順暢運作。

在PHP中使用MySQLi建立資料庫連線的詳盡教學 在PHP中使用MySQLi建立資料庫連線的詳盡教學 Jun 04, 2024 pm 01:42 PM

如何在PHP中使用MySQLi建立資料庫連線:包含MySQLi擴充(require_once)建立連線函數(functionconnect_to_db)呼叫連線函數($conn=connect_to_db())執行查詢($result=$conn->query())關閉連線( $conn->close())

如何使用C++實作HTTP流傳輸? 如何使用C++實作HTTP流傳輸? May 31, 2024 am 11:06 AM

如何在C++中實現HTTP流傳輸?使用Boost.Asio和asiohttps客戶端程式庫建立SSL流套接字。連接到伺服器並發送HTTP請求。接收HTTP響應頭並列印它們。接收HTTP回應正文並列印它。

如何在 Golang 中使用資料庫回呼函數? 如何在 Golang 中使用資料庫回呼函數? Jun 03, 2024 pm 02:20 PM

在Golang中使用資料庫回呼函數可以實現:在指定資料庫操作完成後執行自訂程式碼。透過單獨的函數新增自訂行為,無需編寫額外程式碼。回調函數可用於插入、更新、刪除和查詢操作。必須使用sql.Exec、sql.QueryRow或sql.Query函數才能使用回呼函數。

如何在 Golang 中將 JSON 資料保存到資料庫中? 如何在 Golang 中將 JSON 資料保存到資料庫中? Jun 06, 2024 am 11:24 AM

可以透過使用gjson函式庫或json.Unmarshal函數將JSON資料儲存到MySQL資料庫中。 gjson函式庫提供了方便的方法來解析JSON字段,而json.Unmarshal函數需要一個目標類型指標來解組JSON資料。這兩種方法都需要準備SQL語句和執行插入操作來將資料持久化到資料庫中。

如何使用C++處理資料庫連線和操作? 如何使用C++處理資料庫連線和操作? Jun 01, 2024 pm 07:24 PM

在C++中使用DataAccessObjects(DAO)函式庫連接和操作資料庫,包括建立資料庫連線、執行SQL查詢、插入新記錄和更新現有記錄。具體步驟為:1.包含必要的函式庫語句;2.開啟資料庫檔案;3.建立Recordset物件執行SQL查詢或操作資料;4.遍歷結果或依照特定需求更新記錄。

如何用 Golang 連接遠端資料庫? 如何用 Golang 連接遠端資料庫? Jun 01, 2024 pm 08:31 PM

透過Go標準庫database/sql包,可以連接到MySQL、PostgreSQL或SQLite等遠端資料庫:建立包含資料庫連接資訊的連接字串。使用sql.Open()函數開啟資料庫連線。執行SQL查詢和插入操作等資料庫操作。使用defer關閉資料庫連線以釋放資源。

See all articles