Unity3D教程:与Sqlite数据库直连

前端之家收集整理的这篇文章主要介绍了Unity3D教程:与Sqlite数据库直连前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

环境介绍:

Windows7,Unity3D,sqlite Expert Personal 3

开发语言:

JavaScript

需要的dll文件

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

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

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

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

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

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

  
  
  1. /*Javascriptclassforaccessingsqliteobjects.
  2. Touseit,youneedtomakesureyouCOPYMono.Data.sqliteClient.dllfromwhereveritlivesinyourUnitydirectory
  3. toyourproject'sAssetsfolder
  4. Originallycreatedbydklompmakerin2009
  5. http://forum.unity3d.com/threads...sier-Database-Stuff
  6. Modified2011byAlanChatham*/
  7. //#pragmastrict
  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. */
  3. importSystem.Data;//weimportourdataclass我们先导入我们的数据集
  4. importMono.Data.sqlite;//weimportsqlite我们导入sqlite数据集,也就是Plugins文件夹下的那个dll文件
  5. classdbAccess{
  6. //variablesforbasicqueryaccess
  7. privatevarconnection:String;//数据库的连接字符串,用于建立与特定数据源的连接
  8. privatevardbcon:IDbConnection;//IDbConnection的连接对象,其实就是一个类对象
  9. privatevardbcmd:IDbCommand;//IDbCommand类对象,用来实现操作数据库的命令:注解:我在网上资料看到的如何实现对数据库执行命令:
  10. //首先创建一个IDbConnection连接对象,然后将一条数据库命令赋值给一个字符串,利用这个字符串和连接对象
  11. //就可以创建(new)一个IDbCommand对象了,然后使用提供的方法就可以执行这个命令了。
  12. privatevarreader:IDataReader;//reader的作用就是读取结果集的一个或多个只进结果流
  13. functionOpenDB(p:String){
  14. connection="URI=file:"+p;//wesettheconnectiontoourdatabase
  15. dbcon=newsqliteConnection(connection);
  16. dbcon.Open();//打开数据库连接操作
  17. }
  18. functionBasicQuery(q:String,r:boolean){//runabaicsqlitequery
  19. dbcmd=dbcon.CreateCommand();//createemptycommand
  20. dbcmd.CommandText=q;//fillthecommand
  21. reader=dbcmd.ExecuteReader();//executecommandwhichreturnsareader返回IDataReader的对象,创建IDataReader的对象
  22. if(r){//ifwewanttoreturnthereader
  23. returnreader;//returnthereader返回读取的对象,就是读到了什么东西
  24. }
  25. }
  26. //Thisreturnsa2dimensionalArrayListwithallthe
  27. //datafromthetablerequested
  28. functionReadFullTable(tableName:String){
  29. varquery:String;
  30. query="SELECT*FROM"+tableName;
  31. dbcmd=dbcon.CreateCommand();
  32. dbcmd.CommandText=query;
  33. reader=dbcmd.ExecuteReader();
  34. varreadArray=newArrayList();
  35. while(reader.Read()){
  36. varlineArray=newArrayList();
  37. for(vari=0;i<reader.FieldCount;i++)
  38. lineArray.Add(reader.GetValue(i));//Thisreadstheentriesinarow
  39. readArray.Add(lineArray);//Thismakesanarrayofalltherows
  40. }
  41. returnreadArray;//returnmatches
  42. }
  43. //Thisfunctiondeletesallthedatainthegiventable.Forever.WATCHOUT!Usesparingly,ifatall
  44. functionDeleteTableContents(tableName:String){
  45. varquery:String;
  46. query="DELETEFROM"+tableName;
  47. dbcmd=dbcon.CreateCommand();
  48. dbcmd.CommandText=query;
  49. reader=dbcmd.ExecuteReader();
  50. }
  51. functionCreateTable(name:String,col:Array,colType:Array){//Createatable,name,columnarray,columntypearray
  52. varquery:String;
  53. query="CREATETABLE"+name+"("+col[0]+""+colType[0];
  54. for(vari=1;i<col.length;i++){
  55. query+=","+col+""+colType;
  56. }
  57. query+=")";
  58. dbcmd=dbcon.CreateCommand();//createemptycommand
  59. dbcmd.CommandText=query;//fillthecommand
  60. reader=dbcmd.ExecuteReader();//executecommandwhichreturnsareader
  61. }
  62. functionInsertIntoSingle(tableName:String,colName:String,value:String){//singleinsert
  63. varquery:String;
  64. query="INSERTINTO"+tableName+"("+colName+")"+"VALUES("+value+")";
  65. dbcmd=dbcon.CreateCommand();//createemptycommand
  66. dbcmd.CommandText=query;//fillthecommand
  67. reader=dbcmd.ExecuteReader();//executecommandwhichreturnsareader
  68. }
  69. functionInsertIntoSpecific(tableName:String,values:Array){//Specificinsertwithcolandvalues
  70. varquery:String;
  71. query="INSERTINTO"+tableName+"("+col[0];
  72. for(vari=1;i<col.length;i++){
  73. query+=","+col;
  74. }
  75. query+=")VALUES("+values[0];
  76. for(i=1;i<values.length;i++){
  77. query+=","+values;
  78. }
  79. query+=")";
  80. dbcmd=dbcon.CreateCommand();
  81. dbcmd.CommandText=query;
  82. reader=dbcmd.ExecuteReader();
  83. }
  84. functionInsertInto(tableName:String,values:Array){//basicInsertwithjustvalues
  85. varquery:String;
  86. query="INSERTINTO"+tableName+"VALUES("+values[0];
  87. for(vari=1;i<values.length;i++){
  88. query+=","+values;
  89. }
  90. query+=")";
  91. dbcmd=dbcon.CreateCommand();
  92. dbcmd.CommandText=query;
  93. reader=dbcmd.ExecuteReader();
  94. }
  95. //Thisfunctionreadsasinglecolumn
  96. //wColistheWHEREcolumn,wParistheoperatoryouwanttousetocomparewith,
  97. //andwValueisthevalueyouwanttocompareagainst.
  98. //Ex.-SingleSelectWhere("puppies","breed","earType","=","floppy")
  99. //returnsanarrayofmatchesfromthecommand:SELECTbreedFROMpuppiesWHEREearType=floppy;
  100. functionSingleSelectWhere(tableName:String,itemToSelect:String,wCol:String,wPar:String,wValue:String){//SelectsasingleItem
  101. varquery:String;
  102. query="SELECT"+itemToSelect+"FROM"+tableName+"WHERE"+wCol+wPar+wValue;
  103. dbcmd=dbcon.CreateCommand();
  104. dbcmd.CommandText=query;
  105. reader=dbcmd.ExecuteReader();
  106. varreadArray=newArray();
  107. while(reader.Read()){
  108. readArray.Push(reader.GetString(0));//Fillarraywithallmatches
  109. }
  110. returnreadArray;//returnmatches
  111. }
  112. functionCloseDB(){
  113. reader.Close();//cleaneverythingup
  114. reader=null;
  115. dbcmd.Dispose();
  116. dbcmd=null;
  117. dbcon.Close();
  118. dbcon=null;
  119. }
  120. }

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

  
  
  1. //#pragmastrict
  2. /*ScriptfortestingoutsqliteinJavascript
  3. 2011-AlanChatham
  4. Releasedintothepublicdomain
  5. ThisscriptisaGUIscript-attachittoyourmaincamera.
  6. Itcreates/opensasqlitedatabase,andwiththeGUIyoucanreadandwritetoit.
  7. */
  8. //Thisisthefilepathofthedatabasefilewewanttouse
  9. //Rightnow,it'llloadTestDB.sqdbintheproject'srootfolder.
  10. //Ifonedoesn'texist,itwillbeautomaticallycreated.
  11. publicvarDatabaseName:String="TestDB.sqdb";
  12. //Thisisthenameofthetablewewanttouse
  13. publicvarTableName:String="TestTable";
  14. vardb:dbAccess;
  15. functionStart(){
  16. //GiveourselvesadbAccessobjecttoworkwith,andopenit
  17. db=newdbAccess();
  18. db.OpenDB(DatabaseName);
  19. //Let'smakesurewe'vegotatabletoworkwithaswell!
  20. vartableName=TableName;
  21. varcolumnNames=newArray("firstName","lastName");
  22. varcolumnValues=newArray("text","text");
  23. try{db.CreateTable(tableName,columnNames,columnValues);
  24. }
  25. catch(e){//Donothing-ourtablewasalreadycreated判断表是否被创建了
  26. //-wedon'tcareabouttheerror,wejustdon'twanttoseeit
  27. }
  28. }
  29. //ThesevariablesjustholdinfotodisplayinourGUI
  30. varfirstName:String="FirstName";
  31. varlastName:String="LastName";
  32. varDatabaseEntryStringWidth=100;
  33. varscrollPosition:Vector2;
  34. vardatabaseData:ArrayList=newArrayList();
  35. //ThisGUIprovidesuswithawaytoenterdataintoourdatabase
  36. //aswellasawaytoviewit
  37. functionOnGUI(){
  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. //Thisfirstblockallowsustoenternewentriesintoourtable
  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("Addtodatabase")){
  47. //Insertthedata
  48. InsertRow(firstName,lastName);
  49. //Andupdatethereadoutofthedatabase
  50. databaseData=ReadFullTable();
  51. }
  52. //Thissecondblockgivesusabuttonthatwilldisplay/refreshthecontentsofourdatabase
  53. GUILayout.BeginHorizontal();
  54. if(GUILayout.Button("ReadDatabase"))
  55. databaseData=ReadFullTable();
  56. if(GUILayout.Button("Clear"))
  57. databaseData.Clear();
  58. GUILayout.EndHorizontal();
  59. GUILayout.Label("DatabaseContents");
  60. scrollPosition=GUILayout.BeginScrollView(scrollPosition,GUILayout.Height(100));
  61. for(varline:ArrayListindatabaseData){
  62. GUILayout.BeginHorizontal();
  63. for(varsinline){
  64. GUILayout.Label(s.ToString(),GUILayout.Width(DatabaseEntryStringWidth));
  65. }
  66. GUILayout.EndHorizontal();
  67. }
  68. GUILayout.EndScrollView();
  69. if(GUILayout.Button("DeleteAllData")){
  70. DeleteTableContents();
  71. databaseData=ReadFullTable();
  72. }
  73. GUILayout.EndArea();
  74. }
  75. //Wrapperfunctionforinsertingourspecificentriesintoourspecificdatabaseandtableforthisfile
  76. functionInsertRow(firstName,lastName){
  77. varvalues=newArray(("'"+firstName+"'"),("'"+lastName+"'"));
  78. db.InsertInto(TableName,values);
  79. }
  80. //Wrapperfunction,soweonlymesswithourtable.
  81. functionReadFullTable(){
  82. returndb.ReadFullTable(TableName);
  83. }
  84. //Anotherwrapperfunction...
  85. functionDeleteTableContents(){
  86. db.DeleteTableContents(TableName);
  87. }

运行结果:

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

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

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

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

原文链接:https://www.f2er.com/sqlite/201066.html

猜你在找的Sqlite相关文章