본문 바로가기

프로그램/유니티 데이터베이스

[유니티 데이터베이스] SQLite

728x90
반응형

1. 윈도우 64 bit 환경으로 설정

 (1) File > Build Settings 클릭

 

코더제로 유니티 데이터베이스 SQLite Build Settings
그림. Build Settings

 

 

 (2) Architecture : x86_64 선택

 

코더제로 유니티 데이터베이스 SQLite Architecture x86_64
그림. Architecture x86_64

 

 

2. Sqlite dll 다운로드

 (1) 다운로드 사이트 : https://www.sqlite.org/download.html

 (2) 사이트에서 중간 정도에 Precompiled Binaries for Windows > sqlite-dll-win64-x64-xxxxxxx.zip 파일 다운로드

 

코더제로 유니티 데이터베이스 SQLite sqlite-dll-win64-x64-xxxxxxx.zip 파일 다운로드
그림. sqlite-dll-win64-x64-xxxxxxx.zip 파일 다운로드

 

 

 (3) Project(프로젝트) Assets 폴더 밑에 Plugins를 만든 뒤, sqlite3.def, sqlite3.dll 파일을 넣습니다.  

 

3. Mono.Data.xxx.dll 파일 복사.

  C:\Program Files\Unity\Hub\Editor\2019.x.xxf1\Editor\Data\Mono\lib\mono\2.0에서

  Mono.Data.dll, Mono.Data.Sqlite.dll, Mono.Data.SqliteClient.dll 파일 복사하여 

  Project(프로젝트) Assets 폴더 밑에 Plugins폴더에 파일을 넣습니다.  

 

코더제로 유니티 데이터베이스 SQLite Mono.Data.xxx.dll 파일 복사
그림. Mono.Data.xxx.dll 파일 복사

 

Plugins.zip
0.92MB

 

 

4. DB Browser 

 (1) 다운로드 사이트 : https://sqlitebrowser.org/dl/

 

 (2) 설치 

 

코더제로 유니티 데이터베이스 SQLite DB Browser
그림. DB Browser

 

 

 (3) DB Broser for SQLite 실행 후 새 데이터베이스(N) 클릭

 

코더제로 유니티 데이터베이스 SQLite 새 데이터베이스(N)
그림. 새 데이터베이스(N)

 

 

 (4) 테이블 생성

  ① 테이블 이름을 입력합니다.

  ② 필드 추가를 클릭합니다.

  ③ 필드 타입을 선택합니다.

 

테이터 타입 설명
INTEGER 부호 있는 정수
REAL
부동 소수점 숫자
TEXT
텍스트
BLOB Binary Large Object. 입력 데이터를 그대로 저장

 

  ④ NN : Not Null. 비어 있을 경우 레코드가 생성되지 않습니다.

  ⑤ PK : Primary Key. 레코드 식별자 키로 단 1개의 값만이 존재 가능합니다.

  ⑥ AI : Auto Increment . 자동으로 값이 증가합니다.

  ⑦ U : Unique. 단 1개의 값만이 존재 할 수 있습니다.

  ⑧ 필드 추가한 내용이 자동적으로 쿼리문으로 만들어 집니다.

 

코더제로 유니티 데이터베이스 SQLite 테이블 정의 변경
그림. 테이블 정의 변경

 

 

5. DatabaseAccess.cs

using UnityEngine;
using Mono.Data.Sqlite;

public class DatabaseAccess
{
    private SqliteConnection m_DatabaseConnection;
    private SqliteCommand m_DatabaseCommand;
    private SqliteDataReader m_Reader;

    public DatabaseAccess(string connectionString)
    {
        OpenDatabase(connectionString);
    }

    public void OpenDatabase(string connectionString)
    {
        m_DatabaseConnection = new SqliteConnection(connectionString);
        m_DatabaseConnection.Open();
        Debug.Log("Connected to database");
    }

    public void CloseSqlConnection()
    {
        if (m_DatabaseCommand != null)
        {
            m_DatabaseCommand.Dispose();
        }

        m_DatabaseCommand = null;

        if (m_Reader != null)
        {
            m_Reader.Dispose();
        }

        m_Reader = null;

        if (m_DatabaseConnection != null)
        {
            m_DatabaseConnection.Close();
        }

        m_DatabaseConnection = null;
        Debug.Log("Disconnected from database.");
    }

    public SqliteDataReader ExecuteQuery(string sqlQuery)
    {
        m_DatabaseCommand = m_DatabaseConnection.CreateCommand();
        m_DatabaseCommand.CommandText = sqlQuery;

        m_Reader = m_DatabaseCommand.ExecuteReader();

        return m_Reader;
    }

    public SqliteDataReader ReadFullTable(string tableName)
    {
        string query = "SELECT * FROM " + tableName;
        return ExecuteQuery(query);
    }

    public SqliteDataReader InsertInto(string tableName, string[] values)
    {
        string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
        for (int i = 1; i < values.Length; ++i)
        {
            query += ", " + values[i];
        }
        query += ")";
        return ExecuteQuery(query);
    }

    public SqliteDataReader InsertIntoSpecific(string tableName, string[] cols, string[] values)
    {
        if (cols.Length != values.Length)
        {
            throw new SqliteException("columns.Length != values.Length");
        }
        string query = "INSERT INTO " + tableName + "(" + cols[0];
        for (int i = 1; i < cols.Length; ++i)
        {
            query += ", " + cols[i];
        }
        query += ") VALUES (" + values[0];
        for (int i = 1; i < values.Length; ++i)
        {
            query += ", " + values[i];
        }
        query += ")";
        return ExecuteQuery(query);
    }

    public SqliteDataReader UpdateInto(string tableName, string[] cols, string[] colsvalues, string selectkey, string selectvalue)
    {

        string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsvalues[0];

        for (int i = 1; i < colsvalues.Length; ++i)
        {

            query += ", " + cols[i] + " =" + colsvalues[i];
        }

        query += " WHERE " + selectkey + " = " + selectvalue + " ";

        return ExecuteQuery(query);
    }

    public SqliteDataReader DeleteContents(string tableName)
    {
        string query = "DELETE FROM " + tableName;
        return ExecuteQuery(query);
    }

    public SqliteDataReader CreateTable(string name, string[] col, string[] colType)
    {
        if (col.Length != colType.Length)
        {
            throw new SqliteException("columns.Length != colType.Length");
        }
        string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
        for (int i = 1; i < col.Length; ++i)
        {
            query += ", " + col[i] + " " + colType[i];
        }
        query += ")";
        return ExecuteQuery(query);
    }

    public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] operation, string[] values)
    {
        if (col.Length != operation.Length || operation.Length != values.Length)
        {
            throw new SqliteException("col.Length != operation.Length != values.Length");
        }
        string query = "SELECT " + items[0];
        for (int i = 1; i < items.Length; ++i)
        {
            query += ", " + items[i];
        }
        query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
        for (int i = 1; i < col.Length; ++i)
        {
            query += " AND " + col[i] + operation[i] + "'" + values[0] + "' ";
        }

        return ExecuteQuery(query);
    }
}

 

6. 데모

using UnityEngine;
using System.IO;

public class DemoSqlite : MonoBehaviour
{
    public string m_DatabaseFileName = "TestDatabase.db";
    public string m_TableName = "TestTable1";
    private DatabaseAccess m_DatabaseAccess;

    void Start()
    {
        string filePath = Path.Combine(Application.streamingAssetsPath, m_DatabaseFileName);
        Debug.Log(filePath);
        m_DatabaseAccess = new DatabaseAccess("data source = " + filePath);

        m_DatabaseAccess.CreateTable("TestTable1",
            new string[] { "name", "age" },
            new string[] { "text", "int" });

        m_DatabaseAccess.InsertInto("TestTable1", new string[] { "'Coderzedro'", "'47'" });
        m_DatabaseAccess.InsertInto("TestTable1", new string[] { "'JD'", "'17'" });
        m_DatabaseAccess.InsertInto("TestTable1", new string[] { "'Tiger'", "'47'" });

        m_DatabaseAccess.CloseSqlConnection();
    }
}

 

728x90
반응형