Unity中Sqlite的配置与使用

  最近在做Unity2D游戏开发,数据方面准备使用SQLite数据库。第一次用这个数据库不知道该怎么操作,找了许多资料终于还是解决了,把方法贴在这里记录留念。

首先是:需要准备的几个dll文件
注意:Unity只支持.net 3.5及以下
将上述文件放到:工程路径/Assets/Plugins/
Unity中Sqlite的配置与使用_第1张图片

数据库管理工具选用的Navicat for Sqlite10.0

下面的是连接和测试的代码,源代码是在网上找到的,不过有一点Bug,经过修改后贴在这里:

using UnityEngine;
using Mono.Data.Sqlite;
using System;


public class SqliteDbHelper  {

    /// 
    /// 声明一个连接对象
    /// 
    private SqliteConnection dbConnection;
    /// 
    /// 声明一个操作数据库命令
    /// 
    private SqliteCommand dbCommand;
    /// 
    /// 声明一个读取结果集的一个或多个结果流
    /// 
    private SqliteDataReader reader;
    /// 
    /// 数据库的连接字符串,用于建立与特定数据源的连接
    /// 
    /// 数据库的连接字符串,用于建立与特定数据源的连接
    public SqliteDbHelper(string connectionString)
    {
        OpenDB(connectionString);
        Debug.Log(connectionString);
    }
    public void OpenDB(string connectionString)
    {
        try
        {
            dbConnection = new SqliteConnection(connectionString);
            dbConnection.Open();
            Debug.Log("Connected to db");
        }
        catch (Exception e)
        {
            string temp1 = e.ToString();
            Debug.Log(temp1);
        }
    }
    /// 
    /// 关闭连接
    /// 
    public void CloseSqlConnection()
    {
        if (dbCommand != null)
        {
            dbCommand.Dispose();
        }
        dbCommand = null;
        if (reader != null)
        {
            reader.Dispose();
        }
        reader = null;
        if (dbConnection != null)
        {
            dbConnection.Close();
        }
        dbConnection = null;
        Debug.Log("Disconnected from db.");
    }
    /// 
    /// 执行查询sqlite语句操作
    /// 
    /// 
    /// 
    public SqliteDataReader ExecuteQuery(string sqlQuery)
    {
        dbCommand = dbConnection.CreateCommand();
        dbCommand.CommandText = sqlQuery;
        reader = dbCommand.ExecuteReader();
        return 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 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 Delete(string tableName, string[] cols, string[] colsvalues)
    {
        string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + colsvalues[0];
        for (int i = 1; i < colsvalues.Length; ++i)
        {
            query += " or " + cols[i] + " = " + colsvalues[i];
        }
        Debug.Log(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 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 += ")";
        Debug.Log(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);
    }
}
using UnityEngine;
using System.Data;
public class SqliteDbTest : MonoBehaviour
{
     private SqliteDbHelper db;
    int id = 1;
    void Start()
    {
        //这里是默认在工程路径下
        db = new SqliteDbHelper("Data Source=test.db;");
        Debug.Log(db.ToString());
        /*
         SqliteDbAccess db = new SqliteDbAccess("data source=mydb1.db");
       db.CreateTable("momo",new string[]{"name","qq","email","blog"},
        new string[]{"text","text","text","text"});
       db.CloseSqlConnection();
        */
    }
    public string name = "";
    public string emls = "";

    void OnGUI()
    {

        if (GUILayout.Button("create table"))
        {
            db.CreateTable("mytable", new string[] { "id", "name", "email" }, new string[] { "int", "varchar(20)", "varchar(50)" });
            Debug.Log("create table ok");
        }

        if (GUILayout.Button("insert data"))
        {

            db.InsertInto("mytable",
                         new string[] { "" + (++id), "'锡丞'", "'[email protected]'" });

            Debug.Log("insert table ok");
        }


        if (GUILayout.Button("search database"))
        {
            IDataReader sqReader = db.SelectWhere("mytable", new string[]
    {"name","email"}, new string[] { "id" }, new string[] { "=" }, new string[] { "2" });
            while (sqReader.Read())
            {

                //Debug.Log(
                name = "name=" + sqReader.GetString(sqReader.GetOrdinal("name"));// +
                emls = "email=" + sqReader.GetString(sqReader.GetOrdinal("email"));
                //);
            }

        }
        if (name != "")
        {
            GUI.Label(new Rect(100, 100, 100, 100), name);
            GUI.Label(new Rect(100, 200, 100, 100), emls);
            //  GUILayout.Label(emls);
        }
        if (GUILayout.Button("close database"))
        {
            db.CloseSqlConnection();
            Debug.Log("close table ok");
        }

    }
}

你可能感兴趣的:(Unity与数据库)