게임엔진/Unity

[Unity] SQL 데이터 베이스 연동 SQLite

ShovelingLife 2023. 3. 23. 09:30

1. Sqlite dll 다운로드

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

 

(2) Precompiled Binaries for Windows > 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폴더에 파일을 넣는다.  

플러그인 다운로드

Mono.Data.xxx.dll 파일 복사

4. DB Browser

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

 

 (2) 설치 

DB Browser

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

그림. 새 데이터베 이스(N)

 (4) 테이블 생성

  ① 테이블 이름 입력

  ② 필드 추가 클릭

  ③ 필드 타입 선택

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

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

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

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

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

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

테이블 정의 변경

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();
    }
}

 

출처 : https://coderzero.tistory.com/entry/%EC%9C%A0%EB%8B%88%ED%8B%B0-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%B2%A0%EC%9D%B4%EC%8A%A4-SQLite