首先你需要得到Mono.Data.Sqlite.dll 文件 與System.Data.dll文件。如果你在Mac 操作系統(tǒng)下使用Unity那么很悲劇,找不到這兩個文件,至少我沒能找到。后來我在Windows下的Unity安裝路徑中找到了它。為了方便大家我將這兩個文件上傳至網(wǎng)盤中,如果沒有這兩個文件的朋友請下載。Unity數(shù)據(jù)庫文件.zip
.zip文件下載完畢后直接解壓,然后將Mono.Data.Sqlite.dll 文件 與System.Data.dll文件放在Unity工程中的Assets文件夾中。如下圖所示,兩個文件已經(jīng)放置在Project視圖當中。

Ok ,我們編寫C#腳本,原始文章沒有Unity數(shù)據(jù)庫更新與刪除的方法,我在這里加上更新與刪除的方法,方便大家開發(fā)時使用。因為其實Unity中更新與刪除數(shù)據(jù)庫也是個比較重要的功能。
注意:下面腳本不要綁定在任何游戲對象身上,大家無需把它當作腳本可以當作一個工具類來使用。
[代碼]java代碼:
001 using UnityEngine; 002 003 using System; 004 using System.Collections; 005 using Mono.Data.Sqlite; 006 007 public class DbAccess 008 009 { 010 011 private SqliteConnection dbConnection; 012 013 private SqliteCommand dbCommand; 014 015 private SqliteDataReader reader; 016 017 public DbAccess (string connectionString) 018 019 { 020 021 OpenDB (connectionString); 022 023 } 024 public DbAccess () 025 { 026 027 } 028 029 public void OpenDB (string connectionString) 030 031 { 032 try 033 { 034 dbConnection = new SqliteConnection (connectionString); 035 036 dbConnection.Open (); 037 038 Debug.Log ("Connected to db"); 039 } 040 catch(Exception e) 041 { 042 string temp1 = e.ToString(); 043 Debug.Log(temp1); 044 } 045 046 } 047 048 public void CloseSqlConnection () 049 050 { 051 052 if (dbCommand != null) { 053 054 dbCommand.Dispose (); 055 056 } 057 058 dbCommand = null; 059 060 if (reader != null) { 061 062 reader.Dispose (); 063 064 } 065 066 reader = null; 067 068 if (dbConnection != null) { 069 070 dbConnection.Close (); 071 072 } 073 074 dbConnection = null; 075 076 Debug.Log ("Disconnected from db."); 077 078 } 079 080 public SqliteDataReader ExecuteQuery (string sqlQuery) 081 082 { 083 084 dbCommand = dbConnection.CreateCommand (); 085 086 dbCommand.CommandText = sqlQuery; 087 088 reader = dbCommand.ExecuteReader (); 089 090 return reader; 091 092 } 093 094 public SqliteDataReader ReadFullTable (string tableName) 095 096 { 097 098 string query = "SELECT * FROM " + tableName; 099 100 return ExecuteQuery (query); 101 102 } 103 104 public SqliteDataReader InsertInto (string tableName, string[] values) 105 106 { 107 108 string query = "INSERT INTO " + tableName + " VALUES (" + values[0]; 109 110 for (int i = 1; i < values.Length; ++i) { 111 112 query += ", " + values[i]; 113 114 } 115 116 query += ")"; 117 118 return ExecuteQuery (query); 119 120 } 121 122 public SqliteDataReader UpdateInto (string tableName, string []cols,string []colsvalues,string selectkey,string selectvalue) 123 { 124 125 string query = "UPDATE "+tableName+" SET "+cols[0]+" = "+colsvalues[0]; 126 127 for (int i = 1; i < colsvalues.Length; ++i) { 128 129 query += ", " +cols[i]+" ="+ colsvalues[i];新聞熱點
疑難解答
圖片精選