环境介绍:
Windows7,Unity3D,sqlite Expert Personal 3
开发语言:
JavaScript
需要的dll文件:
Mono.Data.sqlite.dll和sqlite3.dll,dll文件位置,截图:
一定要在这个目录下,请保持一致。
如果需要将编译好的程序发布成功的话,需要改一些地方,具体见下面的截图:
要改动的地方已用红色标记,注意这个要改成.NET2.0,这样才能够发布的。系统默认的不是.NET2.0,这一点要注意!!!
下面来看下代码吧,先看下如何创建数据库的代码,这一篇代码是不用挂到任何对象上面去的,你只用把它当成一个工具即可。如下所示:
- /*Javascriptclassforaccessingsqliteobjects.
- Touseit,youneedtomakesureyouCOPYMono.Data.sqliteClient.dllfromwhereveritlivesinyourUnitydirectory
- toyourproject'sAssetsfolder
- Originallycreatedbydklompmakerin2009
- http://forum.unity3d.com/threads...sier-Database-Stuff
- Modified2011byAlanChatham*/
- //#pragmastrict
- /*
代码描述
*本代码是为了在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;那么这些操作做完了以后,如果你的代码写得没有问题,那么你就可以成功了。
细解释代码:
- *
- */
- importSystem.Data;//weimportourdataclass我们先导入我们的数据集
- importMono.Data.sqlite;//weimportsqlite我们导入sqlite数据集,也就是Plugins文件夹下的那个dll文件
- classdbAccess{
- //variablesforbasicqueryaccess
- privatevarconnection:String;//数据库的连接字符串,用于建立与特定数据源的连接
- privatevardbcon:IDbConnection;//IDbConnection的连接对象,其实就是一个类对象
- privatevardbcmd:IDbCommand;//IDbCommand类对象,用来实现操作数据库的命令:注解:我在网上资料看到的如何实现对数据库执行命令:
- //首先创建一个IDbConnection连接对象,然后将一条数据库命令赋值给一个字符串,利用这个字符串和连接对象
- //就可以创建(new)一个IDbCommand对象了,然后使用提供的方法就可以执行这个命令了。
- privatevarreader:IDataReader;//reader的作用就是读取结果集的一个或多个只进结果流
- functionOpenDB(p:String){
- connection="URI=file:"+p;//wesettheconnectiontoourdatabase
- dbcon=newsqliteConnection(connection);
- dbcon.Open();//打开数据库连接操作
- }
- functionBasicQuery(q:String,r:boolean){//runabaicsqlitequery
- dbcmd=dbcon.CreateCommand();//createemptycommand
- dbcmd.CommandText=q;//fillthecommand
- reader=dbcmd.ExecuteReader();//executecommandwhichreturnsareader返回IDataReader的对象,创建IDataReader的对象
- if(r){//ifwewanttoreturnthereader
- returnreader;//returnthereader返回读取的对象,就是读到了什么东西
- }
- }
- //Thisreturnsa2dimensionalArrayListwithallthe
- //datafromthetablerequested
- functionReadFullTable(tableName:String){
- varquery:String;
- query="SELECT*FROM"+tableName;
- dbcmd=dbcon.CreateCommand();
- dbcmd.CommandText=query;
- reader=dbcmd.ExecuteReader();
- varreadArray=newArrayList();
- while(reader.Read()){
- varlineArray=newArrayList();
- for(vari=0;i<reader.FieldCount;i++)
- lineArray.Add(reader.GetValue(i));//Thisreadstheentriesinarow
- readArray.Add(lineArray);//Thismakesanarrayofalltherows
- }
- returnreadArray;//returnmatches
- }
- //Thisfunctiondeletesallthedatainthegiventable.Forever.WATCHOUT!Usesparingly,ifatall
- functionDeleteTableContents(tableName:String){
- varquery:String;
- query="DELETEFROM"+tableName;
- dbcmd=dbcon.CreateCommand();
- dbcmd.CommandText=query;
- reader=dbcmd.ExecuteReader();
- }
- functionCreateTable(name:String,col:Array,colType:Array){//Createatable,name,columnarray,columntypearray
- varquery:String;
- query="CREATETABLE"+name+"("+col[0]+""+colType[0];
- for(vari=1;i<col.length;i++){
- query+=","+col+""+colType;
- }
- query+=")";
- dbcmd=dbcon.CreateCommand();//createemptycommand
- dbcmd.CommandText=query;//fillthecommand
- reader=dbcmd.ExecuteReader();//executecommandwhichreturnsareader
- }
- functionInsertIntoSingle(tableName:String,colName:String,value:String){//singleinsert
- varquery:String;
- query="INSERTINTO"+tableName+"("+colName+")"+"VALUES("+value+")";
- dbcmd=dbcon.CreateCommand();//createemptycommand
- dbcmd.CommandText=query;//fillthecommand
- reader=dbcmd.ExecuteReader();//executecommandwhichreturnsareader
- }
- functionInsertIntoSpecific(tableName:String,values:Array){//Specificinsertwithcolandvalues
- varquery:String;
- query="INSERTINTO"+tableName+"("+col[0];
- for(vari=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();
- }
- functionInsertInto(tableName:String,values:Array){//basicInsertwithjustvalues
- varquery:String;
- query="INSERTINTO"+tableName+"VALUES("+values[0];
- for(vari=1;i<values.length;i++){
- query+=","+values;
- }
- query+=")";
- dbcmd=dbcon.CreateCommand();
- dbcmd.CommandText=query;
- reader=dbcmd.ExecuteReader();
- }
- //Thisfunctionreadsasinglecolumn
- //wColistheWHEREcolumn,wParistheoperatoryouwanttousetocomparewith,
- //andwValueisthevalueyouwanttocompareagainst.
- //Ex.-SingleSelectWhere("puppies","breed","earType","=","floppy")
- //returnsanarrayofmatchesfromthecommand:SELECTbreedFROMpuppiesWHEREearType=floppy;
- functionSingleSelectWhere(tableName:String,itemToSelect:String,wCol:String,wPar:String,wValue:String){//SelectsasingleItem
- varquery:String;
- query="SELECT"+itemToSelect+"FROM"+tableName+"WHERE"+wCol+wPar+wValue;
- dbcmd=dbcon.CreateCommand();
- dbcmd.CommandText=query;
- reader=dbcmd.ExecuteReader();
- varreadArray=newArray();
- while(reader.Read()){
- readArray.Push(reader.GetString(0));//Fillarraywithallmatches
- }
- returnreadArray;//returnmatches
- }
- functionCloseDB(){
- reader.Close();//cleaneverythingup
- reader=null;
- dbcmd.Dispose();
- dbcmd=null;
- dbcon.Close();
- dbcon=null;
- }
- }
- //#pragmastrict
- /*ScriptfortestingoutsqliteinJavascript
- 2011-AlanChatham
- Releasedintothepublicdomain
- ThisscriptisaGUIscript-attachittoyourmaincamera.
- Itcreates/opensasqlitedatabase,andwiththeGUIyoucanreadandwritetoit.
- */
- //Thisisthefilepathofthedatabasefilewewanttouse
- //Rightnow,it'llloadTestDB.sqdbintheproject'srootfolder.
- //Ifonedoesn'texist,itwillbeautomaticallycreated.
- publicvarDatabaseName:String="TestDB.sqdb";
- //Thisisthenameofthetablewewanttouse
- publicvarTableName:String="TestTable";
- vardb:dbAccess;
- functionStart(){
- //GiveourselvesadbAccessobjecttoworkwith,andopenit
- db=newdbAccess();
- db.OpenDB(DatabaseName);
- //Let'smakesurewe'vegotatabletoworkwithaswell!
- vartableName=TableName;
- varcolumnNames=newArray("firstName","lastName");
- varcolumnValues=newArray("text","text");
- try{db.CreateTable(tableName,columnNames,columnValues);
- }
- catch(e){//Donothing-ourtablewasalreadycreated判断表是否被创建了
- //-wedon'tcareabouttheerror,wejustdon'twanttoseeit
- }
- }
- //ThesevariablesjustholdinfotodisplayinourGUI
- varfirstName:String="FirstName";
- varlastName:String="LastName";
- varDatabaseEntryStringWidth=100;
- varscrollPosition:Vector2;
- vardatabaseData:ArrayList=newArrayList();
- //ThisGUIprovidesuswithawaytoenterdataintoourdatabase
- //aswellasawaytoviewit
- functionOnGUI(){
- GUI.Box(Rect(25,25,Screen.width-50,Screen.height-50),"Data");
- GUILayout.BeginArea(Rect(50,50,Screen.width-100,Screen.height-100));
- //Thisfirstblockallowsustoenternewentriesintoourtable
- GUILayout.BeginHorizontal();
- firstName=GUILayout.TextField(firstName,GUILayout.Width(DatabaseEntryStringWidth));
- lastName=GUILayout.TextField(lastName,GUILayout.Width(DatabaseEntryStringWidth));
- //lastName=GUILayout.TextField();
- GUILayout.EndHorizontal();
- if(GUILayout.Button("Addtodatabase")){
- //Insertthedata
- InsertRow(firstName,lastName);
- //Andupdatethereadoutofthedatabase
- databaseData=ReadFullTable();
- }
- //Thissecondblockgivesusabuttonthatwilldisplay/refreshthecontentsofourdatabase
- GUILayout.BeginHorizontal();
- if(GUILayout.Button("ReadDatabase"))
- databaseData=ReadFullTable();
- if(GUILayout.Button("Clear"))
- databaseData.Clear();
- GUILayout.EndHorizontal();
- GUILayout.Label("DatabaseContents");
- scrollPosition=GUILayout.BeginScrollView(scrollPosition,GUILayout.Height(100));
- for(varline:ArrayListindatabaseData){
- GUILayout.BeginHorizontal();
- for(varsinline){
- GUILayout.Label(s.ToString(),GUILayout.Width(DatabaseEntryStringWidth));
- }
- GUILayout.EndHorizontal();
- }
- GUILayout.EndScrollView();
- if(GUILayout.Button("DeleteAllData")){
- DeleteTableContents();
- databaseData=ReadFullTable();
- }
- GUILayout.EndArea();
- }
- //Wrapperfunctionforinsertingourspecificentriesintoourspecificdatabaseandtableforthisfile
- functionInsertRow(firstName,lastName){
- varvalues=newArray(("'"+firstName+"'"),("'"+lastName+"'"));
- db.InsertInto(TableName,values);
- }
- //Wrapperfunction,soweonlymesswithourtable.
- functionReadFullTable(){
- returndb.ReadFullTable(TableName);
- }
- //Anotherwrapperfunction...
- functionDeleteTableContents(){
- db.DeleteTableContents(TableName);
- }
运行结果:
这是在Unity3D中运行的结果,数据的操作结果如下:
原文链接:http://bbs.9ria.com/forum.PHP?mod=viewthread&tid=168629&fromuid=308561
原文链接:https://www.f2er.com/sqlite/201066.html