Unity3D教程:與Sqlite數(shù)據(jù)庫直連
環(huán)境介紹:
Windows7,Unity3D,SQLite Expert Personal 3
開發(fā)語言:
JavaScript
需要的dll文件:
Mono.Data.Sqlite.dll和sqlite3.dll,dll文件位置,截圖:

Unity3D教程:Unity3D與Sqlite數(shù)據(jù)庫直連
一定要在這個(gè)目錄下,請保持一致。
如果需要將編譯好的程序發(fā)布成功的話,需要改一些地方,具體見下面的截圖:

要改動的地方已用紅色標(biāo)記,注意這個(gè)要改成.NET2.0,這樣才能夠發(fā)布的。系統(tǒng)默認(rèn)的不是.NET2.0,這一點(diǎn)要注意?。?!
下面來看下代碼吧,先看下如何創(chuàng)建數(shù)據(jù)庫的代碼,這一篇代碼是不用掛到任何對象上面去的,你只用把它當(dāng)成一個(gè)工具即可。如下所示:
- /* 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環(huán)境下運(yùn)行unity3d和Sqlite數(shù)據(jù)庫而寫的;實(shí)現(xiàn)的基本功能是unity3d能夠與數(shù)據(jù)庫之間進(jìn)行基本的通信,比如說:在數(shù)據(jù)庫中的數(shù)據(jù)被改變了以后,unity3d中得到的數(shù)據(jù)也會在刷新了之后跟著改變;這只是一個(gè)基本的核心的技術(shù),為的是能夠應(yīng)用在大型的unity3d項(xiàng)目中,能夠存儲場景中的項(xiàng)目的屬性,在需要改變對象的屬性或增加、減少等對象時(shí)能夠很方便的用得上。要實(shí)現(xiàn)本代碼。首先需要一些dll文件,一個(gè)是Mono.Data.SQLiteClient.dll,另外一個(gè)是sqlite3.dll,這些文件都能夠在unity3d的安裝目錄中找得到。除此之外,還需要把這兩個(gè)文件放在你的項(xiàng)目的這個(gè)路徑下面:\Assets\Plugins\,沒有Plugins文件夾就必須創(chuàng)建這個(gè)文件夾,然后將這兩個(gè)dll文件放在該文件夾寫。當(dāng)然,如果你想能夠在PC上面發(fā)布成可執(zhí)行文件,還需要改動一些地方。在unity3d中的Play Setting ->Other Setting 中將Api Compatibility的等級改為.NET 2.0;那么這些操作做完了以后,如果你的代碼寫得沒有問題,那么你就可以成功了。
細(xì)解釋代碼:
- *
 - */
 - import System.Data; // we import our data class 我們先導(dǎo)入我們的數(shù)據(jù)集
 - import Mono.Data.Sqlite; // we import sqlite 我們導(dǎo)入sqlite數(shù)據(jù)集,也就是Plugins文件夾下的那個(gè)dll文件
 - class dbAccess {
 - // variables for basic query access
 - private var connection : String; //數(shù)據(jù)庫的連接字符串,用于建立與特定數(shù)據(jù)源的連接
 - private var dbcon : IDbConnection; //IDbConnection的連接對象,其實(shí)就是一個(gè)類對象
 - private var dbcmd : IDbCommand; //IDbCommand類對象,用來實(shí)現(xiàn)操作數(shù)據(jù)庫的命令:注解:我在網(wǎng)上資料看到的如何實(shí)現(xiàn)對數(shù)據(jù)庫執(zhí)行命令:
 - //首先創(chuàng)建一個(gè)IDbConnection連接對象,然后將一條數(shù)據(jù)庫命令賦值給一個(gè)字符串,利用這個(gè)字符串和連接對象
 - //就可以創(chuàng)建(new)一個(gè)IDbCommand對象了,然后使用提供的方法就可以執(zhí)行這個(gè)命令了。
 - private var reader : IDataReader; //reader的作用就是讀取結(jié)果集的一個(gè)或多個(gè)只進(jìn)結(jié)果流
 - function OpenDB(p : String){
 - connection = "URI=file:" + p; // we set the connection to our database
 - dbcon = new SqliteConnection(connection);
 - dbcon.Open(); //打開數(shù)據(jù)庫連接操作
 - }
 - function BasicQuery(q : String, r : boolean){ // run a baic Sqlite query
 - dbcmd = dbcon.CreateCommand(); // create empty command
 - dbcmd.CommandText = q; // fill the command
 - reader = dbcmd.ExecuteReader(); // execute command which returns a reader 返回IDataReader的對象,創(chuàng)建IDataReader的對象
 - if(r){ // if we want to return the reader
 - return reader; // return the reader 返回讀取的對象,就是讀到了什么東西
 - }
 - }
 - // This returns a 2 dimensional ArrayList with all the
 - // data from the table requested
 - function ReadFullTable(tableName : String){
 - var query : String;
 - query = "SELECT * FROM " + tableName;
 - dbcmd = dbcon.CreateCommand();
 - dbcmd.CommandText = query;
 - reader = dbcmd.ExecuteReader();
 - var readArray = new ArrayList();
 - while(reader.Read()){
 - var lineArray = new ArrayList();
 - for (var i = 0; i < reader.FieldCount; i++)
 - lineArray.Add(reader.GetValue(i)); // This reads the entries in a row
 - readArray.Add(lineArray); // This makes an array of all the rows
 - }
 - return readArray; // return matches
 - }
 - // This function deletes all the data in the given table. Forever. WATCH OUT! Use sparingly, if at all
 - function DeleteTableContents(tableName : String){
 - var query : String;
 - query = "DELETE FROM " + tableName;
 - dbcmd = dbcon.CreateCommand();
 - dbcmd.CommandText = query;
 - reader = dbcmd.ExecuteReader();
 - }
 - function CreateTable(name : String, col : Array, colType : Array){ // Create a table, name, column array, column type array
 - var query : String;
 - query = "CREATE TABLE " + name + "(" + col[0] + " " + colType[0];
 - for(var i=1; i<col.length; i++){
 - query += ", " + col + " " + colType;
 - }
 - query += ")";
 - dbcmd = dbcon.CreateCommand(); // create empty command
 - dbcmd.CommandText = query; // fill the command
 - reader = dbcmd.ExecuteReader(); // execute command which returns a reader
 - }
 - function InsertIntoSingle(tableName : String, colName : String, value : String){ // single insert
 - var query : String;
 - query = "INSERT INTO " + tableName + "(" + colName + ") " + "VALUES (" + value + ")";
 - dbcmd = dbcon.CreateCommand(); // create empty command
 - dbcmd.CommandText = query; // fill the command
 - reader = dbcmd.ExecuteReader(); // execute command which returns a reader
 - }
 - function InsertIntoSpecific(tableName : String, col : Array, values : Array){ // Specific insert with col and values
 - var query : String;
 - query = "INSERT INTO " + tableName + "(" + col[0];
 - for(var i=1; i<col.length; i++){
 - query += ", " + col;
 - }
 - query += ") VALUES (" + values[0];
 - for(i=1; i<values.length; i++){
 - query += ", " + values;
 - }
 - query += ")";
 - dbcmd = dbcon.CreateCommand();
 - dbcmd.CommandText = query;
 - reader = dbcmd.ExecuteReader();
 - }
 - function InsertInto(tableName : String, values : Array){ // basic Insert with just values
 - var query : String;
 - query = "INSERT INTO " + tableName + " VALUES (" + values[0];
 - for(var i=1; i<values.length; i++){
 - query += ", " + values;
 - }
 - query += ")";
 - dbcmd = dbcon.CreateCommand();
 - dbcmd.CommandText = query;
 - reader = dbcmd.ExecuteReader();
 - }
 - // This function reads a single column
 - // wCol is the WHERE column, wPar is the operator you want to use to compare with,
 - // and wValue is the value you want to compare against.
 - // Ex. - SingleSelectWhere("puppies", "breed", "earType", "=", "floppy")
 - // returns an array of matches from the command: SELECT breed FROM puppies WHERE earType = floppy;
 - function SingleSelectWhere(tableName : String, itemToSelect : String, wCol : String, wPar : String, wValue : String){ // Selects a single Item
 - var query : String;
 - query = "SELECT " + itemToSelect + " FROM " + tableName + " WHERE " + wCol + wPar + wValue;
 - dbcmd = dbcon.CreateCommand();
 - dbcmd.CommandText = query;
 - reader = dbcmd.ExecuteReader();
 - var readArray = new Array();
 - while(reader.Read()){
 - readArray.Push(reader.GetString(0)); // Fill array with all matches
 - }
 - return readArray; // return matches
 - }
 - function CloseDB(){
 - reader.Close(); // clean everything up
 - reader = null;
 - dbcmd.Dispose();
 - dbcmd = null;
 - dbcon.Close();
 - dbcon = null;
 - }
 - }
 7、如何在Unity3D中使用這個(gè)數(shù)據(jù)庫的代碼:
- //#pragma strict
 - /* Script for testing out SQLite in Javascript
 - 2011 - Alan Chatham
 - Released into the public domain
 - This script is a GUI script - attach it to your main camera.
 - It creates/opens a SQLite database, and with the GUI you can read and write to it.
 - */
 - // This is the file path of the database file we want to use
 - // Right now, it'll load TestDB.sqdb in the project's root folder.
 - // If one doesn't exist, it will be automatically created.
 - public var DatabaseName : String = "TestDB.sqdb";
 - // This is the name of the table we want to use
 - public var TableName : String = "TestTable";
 - var db : dbAccess;
 - function Start(){
 - // Give ourselves a dbAccess object to work with, and open it
 - db = new dbAccess();
 - db.OpenDB(DatabaseName);
 - // Let's make sure we've got a table to work with as well!
 - var tableName = TableName;
 - var columnNames = new Array("firstName","lastName");
 - var columnValues = new Array("text","text");
 - try {db.CreateTable(tableName,columnNames,columnValues);
 - }
 - catch(e){// Do nothing - our table was already created判斷表是否被創(chuàng)建了
 - //- we don't care about the error, we just don't want to see it
 - }
 - }
 - // These variables just hold info to display in our GUI
 - var firstName : String = "First Name";
 - var lastName : String = "Last Name";
 - var DatabaseEntryStringWidth = 100;
 - var scrollPosition : Vector2;
 - var databaseData : ArrayList = new ArrayList();
 - // This GUI provides us with a way to enter data into our database
 - // as well as a way to view it
 - function OnGUI(){
 - GUI.Box(Rect (25,25,Screen.width - 50, Screen.height - 50),"Data");
 - GUILayout.BeginArea(Rect(50, 50, Screen.width - 100, Screen.height - 100));
 - // This first block allows us to enter new entries into our table
 - GUILayout.BeginHorizontal();
 - firstName = GUILayout.TextField(firstName, GUILayout.Width (DatabaseEntryStringWidth));
 - lastName = GUILayout.TextField(lastName, GUILayout.Width (DatabaseEntryStringWidth));
 - //lastName = GUILayout.TextField();
 - GUILayout.EndHorizontal();
 - if (GUILayout.Button("Add to database")){
 - // Insert the data
 - InsertRow(firstName,lastName);
 - // And update the readout of the database
 - databaseData = ReadFullTable();
 - }
 - // This second block gives us a button that will display/refresh the contents of our database
 - GUILayout.BeginHorizontal();
 - if (GUILayout.Button ("Read Database"))
 - databaseData = ReadFullTable();
 - if (GUILayout.Button("Clear"))
 - databaseData.Clear();
 - GUILayout.EndHorizontal();
 - GUILayout.Label("Database Contents");
 - scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(100));
 - for (var line : ArrayList in databaseData){
 - GUILayout.BeginHorizontal();
 - for (var s in line){
 - GUILayout.Label(s.ToString(), GUILayout.Width(DatabaseEntryStringWidth));
 - }
 - GUILayout.EndHorizontal();
 - }
 - GUILayout.EndScrollView();
 - if (GUILayout.Button("Delete All Data")){
 - DeleteTableContents();
 - databaseData = ReadFullTable();
 - }
 - GUILayout.EndArea();
 - }
 - // Wrapper function for inserting our specific entries into our specific database and table for this file
 - function InsertRow(firstName, lastName){
 - var values = new Array(("'"+firstName+"'"),("'"+lastName+"'"));
 - db.InsertInto(TableName, values);
 - }
 - // Wrapper function, so we only mess with our table.
 - function ReadFullTable(){
 - return db.ReadFullTable(TableName);
 - }
 - // Another wrapper function...
 - function DeleteTableContents(){
 - db.DeleteTableContents(TableName);
 - }
 
運(yùn)行結(jié)果:
這是在Unity3D中運(yùn)行的結(jié)果,數(shù)據(jù)的操作結(jié)果如下:
我們看見了數(shù)據(jù)的操作能夠成功,經(jīng)過測試,其他的Button也都能出現(xiàn)相對應(yīng)的效果,那我們再看看這個(gè)到底有沒有生成我們想要的數(shù)據(jù)庫文件:
文件當(dāng)中數(shù)據(jù):經(jīng)測試,我們在對數(shù)據(jù)庫中的數(shù)據(jù)進(jìn)行操作的時(shí)候,我們的Unity3D中的數(shù)據(jù)也會發(fā)生相應(yīng)的改變了!
原文鏈接:http://bbs.9ria.com/forum.php?mod=viewthread&tid=168629&fromuid=308561















 
 
 
 
 
 
 