Search
Duplicate

Unity/ SQLite Unity Kit

설치

아래의 링크에서 파일을 받을 수 있다.
파일을 열면 readme 파일을 제외하고 3개의 파일이 있다
DataTable.cs
SqliteDatabase.cs
libsqlite3.so
3개의 파일 중에 DataTable.cs와 SqliteDatabase.cs 파일은 플러그인 폴더에 넣고 –플러그인 폴더에 SQLiteUnityKit 폴더를 만들어서 넣는다– libsqlite3.so 파일은 안드로이드 빌드용 파일이므로 plugin/android 폴더 아래에 넣는다.

DB 파일 저장 위치

게임 내에서 사용할 DB 파일을 만들었다면 Assets/StreamingAssets 폴더 아래에 둔다.
이렇게 해두면 플러그인의 코드는 StreamingAssets 폴더 아래에 있는 db 파일을 원본으로 보고, 그 파일을 유니티에서 지원하는 persistentDataPath 에 복사해서 게임 내에서 사용할 것이다.

게임 내에서 DB 파일 불러오기

게임 내에서 DB 파일을 불러 올 때는 SqliteDatabase 생성자에 db 파일의 이름을 string으로 넘기면 된다.
static SqliteDatabase vocaDB; static SqliteDatabase quizEngDB; static public void InitQuizDictionary () { quizEngDB = new SqliteDatabase("quiz_english.sqlite"); vocaDB = new SqliteDatabase("vocabulary.sqlite"); }
C#
복사
게임 내에서 사용되는 DB 파일은 persistentDataPath에 들어가게 되는데, 만일 persistentDataPath에 DB 파일이 없다면, 플러그인 코드는 streamingAssetsPath –Assets/StreamingAssets– 에서 DB 파일을 persistentDataPath에 복사해 와서 사용할 것이다.
때문에 streamingAssetsPath에도 파일이 없으면 에러가 난다.

DB 파일 최신 버전으로 변경하기

사용하는 DB가 업데이트 되어 DB 파일을 교체 해야 하는 경우 아래와 같이 DB 파일이 변경된 것을 확인하여 갈아 치우는 로직을 사용한다.
// 일단 vocaDB 를 생성한 후에 vocaDB이 업데이트 되었는지 확인한다. vocaDB = new SqliteDatabase("vocabulary.sqlite"); vocaDB.OverwriteOnSourceMismatch("vocabulary.sqlite"); // OverwriteOnSourceMismatch가 DB 파일 업데이트를 체크하는 부분. MD5를 이용해서 버전이 바뀌었는지를 확인한다. public bool OverwriteOnSourceMismatch(string dbName) { string sourceDbPath = System.IO.Path.Combine (Application.streamingAssetsPath, dbName); string currentDbPath = System.IO.Path.Combine (Application.persistentDataPath, dbName); if (System.IO.File.Exists(currentDbPath) && System.IO.File.Exists(sourceDbPath)) { String sourceDbChecksum = CreateMD5HashOfFile(sourceDbPath); String currentDbChecksum = CreateMD5HashOfFile(currentDbPath); if (currentDbChecksum != sourceDbChecksum) { CopyDB (sourceDbPath, currentDbPath); return true; } } return false; } // 버전이 바뀌었는지를 체크하는 MD5 부분. private string CreateMD5HashOfFile(string filename) { // Use input string to calculate MD5 hash System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); System.IO.FileStream stream = System.IO.File.OpenRead(filename); byte[] hashBytes = md5.ComputeHash(stream); // Convert the byte array to hexadecimal string System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sb.Append (hashBytes[i].ToString ("X2")); // To force the hex string to lower-case letters instead of // upper-case, use he following line instead: // sb.Append(hashBytes[i].ToString("x2")); } return sb.ToString(); }
C#
복사

DB 파일 사용하기

DB에 값을 읽거나 쓸 때는 그것을 하기 전에 먼저 Open을 하고 쿼리를 날린 후에는 Close를 해야 하는데, 이는 SQLite Unity Kit 플러그인 코드에 구현되어 있다. 따라서 그냥 값을 읽거나 쓰기를 시도하면 알아서 open하고 처리가 끝나면 자동으로 close 해줌.

DB에서 값을 읽어 오기

DB에 쿼리를 날려 값을 읽어올 때는 SELECT 구문을 사용하는 ExecuteQuery를 사용한다.
DataTable maxLevelResult = vocaDB.ExecuteQuery("SELECT MAX(level) FROM vocabulary");
C#
복사
DB에 쿼리를 날리면 DataTable 형태의 값을 리턴해 준다. DataTable은 아래와 같이 생겼다.
public DataTable() { Columns = new List<string>(); Rows = new List<DataRow>(); }
C#
복사
Row를 구성하는 DataRow는 아래와 같이 생겼다.
public class DataRow : Dictionary<string, object> { public new object this[string column] { get { if (ContainsKey(column)) { return base[column]; } return null; } set { if (ContainsKey(column)) { base[column] = value; } else { Add(column, value); } } } }
C#
복사

DB에 값을 쓰기

DB에 쿼리를 날려 값을 쓸 때는 INSERT/UPDATE/DELETE 구문을 사용하는 ExecuteNonQuery를 사용한다.
quizEngDB.ExecuteNonQuery("INSERT INTO WordActivity (word, level) VALUES ('" + Word + "', " + Level + ")"); quizEngDB.ExecuteNonQuery("UPDATE WordActivity SET " + "quized_count = " + totalQuizedCount + ", " + "incorrect_count = " + totalIncorrectCount + ", " + "unhinted_correct_count = " + totalUnhintedCorrectCount + ", " + "hinted_correct_count = " + totalHintedCorrectCount + " " + "WHERE word = '" + Word + "'");
C#
복사