LoginSignup
1
1

More than 5 years have passed since last update.

UnityでSQLiteを使用する for iOS

Last updated at Posted at 2018-01-16

SQLiteUnityKit
https://github.com/Busta117/SQLiteUnityKit

プロジェクトに配置

Unity - マニュアル:特殊なフォルダー名
https://docs.unity3d.com/jp/530/Manual/SpecialFolders.html

ライブラリは Plugins フォルダ配下に設置します。

Assets
    Plugins
        iOS
            libsqlite3.so

スクリプトを配置します。

Assets
    Scripts
        DataTable.cs
        SqliteDatabase.cs       

SQLite のデータベースファイルはコピーして使用されるように StreamingAssets 配下に設置します。

Assets
    StreamingAssets
        test.db

Application.persistentDataPath で取得されるパスにコピーされます。
コピーされたファイルに対してクエリが適用されます。

/Users/{ACCOUNT}/Library/Application Support/DefaultCompany/{PROJECT}

クエリの実行

データベースの読み込み

SqliteDatabase db = new SqliteDatabase ("test.db");

データ登録(または削除)

.ExecuteNonQuery() を使用します。

string query1 = "INSETR INTO TEST_MST VALUES (1, 'name')";
db.ExecuteNonQuery(query1);

データ取得

.ExecuteQuery() を使用します。

string query2 = "SELECT * FROM TEST_MST";
DataTable dataTable = db.ExecuteQuery(query2);

foreach(DataRow row in dataTable.Rows){
    int id = (int)row["id"];
    string name = (string)row["name"];
    Debug.Log ("id= " + id + ", name=" + name);
}

マルチバイト問題

英語圏で作成されたライブラリのためマルチバイトに対応しておらず、クエリにマルチバイト文字が含まれるとクエリエラーが発生します。

Prepare メソッド内でクエリ文字数を処理している箇所を修正します。

SqliteDatabase.cs
// Query の文字数をマルチバイトを考慮して取得する
int length = System.Text.Encoding.GetEncoding("UTF-8").GetByteCount(query);
// query.Length を置換する
if (sqlite3_prepare_v2 (_connection, query, length, out stmHandle, IntPtr.Zero) != SQLITE_OK) {

StreamingAssets コピー置換仕様

SqliteDatabase.cs
if (!System.IO.File.Exists (pathDB) || (System.IO.File.GetLastWriteTimeUtc(sourcePath) > System.IO.File.GetLastWriteTimeUtc(pathDB))) {

ファイルが存在しない、または タイムスタンプが古い場合にコピー置換される仕様 になっているため、マスタを更新したアプリアップデートを行うと上書きされます。

そのため、データベースにマスタ以外のユーザデータを作成・更新などしている実装を行う場合は適宜対応が必要になります。

要注意点です。

  • タイムスタンプの比較条件を消す
  • フラグを渡して true のときのみコピーする
  • ユーザデータのバックアップを取ってからコピーしユーザデータを入れ直す
  • ユーザデータの DB を分けてそのファイルは置換しないようにする

など対応します。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1