Unity3D开发之SQLite本地数据库

欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群


 

所需工具:包含所需的库文件跟数据库可视化工具AqLiteStudio

https://download.csdn.net/download/qq_37310110/11341017

一:工具类:

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

public class SQLiteHelper
{
    /// 
    /// 数据库连接定义
    /// 
    private SqliteConnection dbConnection;

    /// 
    /// SQL命令定义
    /// 
    private SqliteCommand dbCommand;

    /// 
    /// 数据读取定义
    /// 
    private SqliteDataReader dataReader;

    /// 
    /// 构造函数    
    /// 
    /// 数据库连接字符串
    public SQLiteHelper(string connectionString)
    {
        try
        {
            //构造数据库连接
            dbConnection = new SqliteConnection(connectionString);
            //打开数据库
            dbConnection.Open();
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }

    /// 
    /// 执行SQL命令
    /// 
    /// The query.
    /// SQL命令字符串
    public SqliteDataReader ExecuteQuery(string queryString)
    {
        dbCommand = dbConnection.CreateCommand();
        dbCommand.CommandText = queryString;
        dataReader = dbCommand.ExecuteReader();
        return dataReader;
    }

    /// 
    /// 关闭数据库连接
    /// 
    public void CloseConnection()
    {
        //销毁Command
        if (dbCommand != null)
        {
            dbCommand.Cancel();
        }
        dbCommand = null;

        //销毁Reader
        if (dataReader != null)
        {
            dataReader.Close();
        }
        dataReader = null;

        //销毁Connection
        if (dbConnection != null)
        {
            dbConnection.Close();
        }
        dbConnection = null;
    }

    /// 
    /// 读取整张数据表
    /// 
    /// The full table.
    /// 数据表名称
    public SqliteDataReader ReadFullTable(string tableName)
    {
        string queryString = "SELECT * FROM " + tableName;
        return ExecuteQuery(queryString);
    }

    /// 
    /// 向指定数据表中插入数据
    /// 
    /// The values.
    /// 数据表名称
    /// 插入的数值
    public SqliteDataReader InsertValues(string tableName, string[] values)
    {
        //获取数据表中字段数目
        int fieldCount = ReadFullTable(tableName).FieldCount;
        //当插入的数据长度不等于字段数目时引发异常
        if (values.Length != fieldCount)
        {
            throw new SqliteException("values.Length!=fieldCount");
        }

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

    /// 
    /// 更新指定数据表内的数据
    /// 
    /// The values.
    /// 数据表名称
    /// 字段名
    /// 字段名对应的数据
    /// 关键字
    /// 关键字对应的值
    public SqliteDataReader UpdateValues(string tableName, string[] colNames, string[] colValues, string key, string operation, string value)
    {
        //当字段名称和字段数值不对应时引发异常
        if (colNames.Length != colValues.Length)
        {
            throw new SqliteException("colNames.Length!=colValues.Length");
        }

        string queryString = "UPDATE " + tableName + " SET " + colNames[0] + "=" + colValues[0];
        for (int i = 1; i < colValues.Length; i++)
        {
            queryString += ", " + colNames[i] + "=" + colValues[i];
        }
        queryString += " WHERE " + key + operation + value;
        return ExecuteQuery(queryString);
    }

    /// 
    /// 删除指定数据表内的数据
    /// 
    /// The values.
    /// 数据表名称
    /// 字段名
    /// 字段名对应的数据
    public SqliteDataReader DeleteValuesOR(string tableName, string[] colNames, string[] operations, string[] colValues)
    {
        //当字段名称和字段数值不对应时引发异常
        if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
        {
            throw new SqliteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
        }

        string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + colValues[0];
        for (int i = 1; i < colValues.Length; i++)
        {
            queryString += "OR " + colNames[i] + operations[0] + colValues[i];
        }
        return ExecuteQuery(queryString);
    }

    /// 
    /// 删除指定数据表内的数据
    /// 
    /// The values.
    /// 数据表名称
    /// 字段名
    /// 字段名对应的数据
    public SqliteDataReader DeleteValuesAND(string tableName, string[] colNames, string[] operations, string[] colValues)
    {
        //当字段名称和字段数值不对应时引发异常
        if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
        {
            throw new SqliteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
        }

        string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + colValues[0];
        for (int i = 1; i < colValues.Length; i++)
        {
            queryString += " AND " + colNames[i] + operations[i] + colValues[i];
        }
        return ExecuteQuery(queryString);
    }

    /// 
    /// 创建数据表
    ///  +
    /// The table.
    /// 数据表名
    /// 字段名
    /// 字段名类型
    public SqliteDataReader CreateTable(string tableName, string[] colNames, string[] colTypes)
    {
        string queryString = "CREATE TABLE " + tableName + "( " + colNames[0] + " " + colTypes[0];
        for (int i = 1; i < colNames.Length; i++)
        {
            queryString += ", " + colNames[i] + " " + colTypes[i];
        }
        queryString += "  ) ";
        return ExecuteQuery(queryString);
    }

    /// 
    /// Reads the table.
    /// 
    /// The table.
    /// Table name.
    /// Items.
    /// Col names.
    /// Operations.
    /// Col values.
    public SqliteDataReader ReadTable(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues)
    {
        string queryString = "SELECT " + items[0];
        for (int i = 1; i < items.Length; i++)
        {
            queryString += ", " + items[i];
        }
        queryString += " FROM " + tableName + " WHERE " + colNames[0] + " " + operations[0] + " " + colValues[0];
        for (int i = 0; i < colNames.Length; i++)
        {
            queryString += " AND " + colNames[i] + " " + operations[i] + " " + colValues[0] + " ";
        }
        return ExecuteQuery(queryString);
    }
}

二:测试类

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

public class SQLiteDemo : MonoBehaviour
{
    /// 
    /// SQLite数据库辅助类
    /// 
    private SQLiteHelper sql;

    void Start()
    {
        //各平台下数据库存储的绝对路径(通用)
        //PC:("data source=" + Application.dataPath + "/幻世界.db");
        //Mac:("data source=" + Application.dataPath + "/幻世界.db");
        //Android:("URI=file:" + Application.persistentDataPath + "/幻世界.db");
        //iOS:("data source=" + Application.persistentDataPath + "/幻世界.db");


        sql = new SQLiteHelper("data source=121.db");

        //1.创建名为table1的数据表
        sql.CreateTable("UserInfo", new string[] { "UniqueID", "Name", "Age", "PhoneNum" }, new string[] { "int", "string", "int", "string" });

        //插入两条数据
        sql.InsertValues("UserInfo", new string[] { "'1'", "'张乐'", "'22'", "'18563215897'" });
        sql.InsertValues("UserInfo", new string[] { "'2'", "'李奇端'", "'25'", "'1683245892'" });

        //更新数据,将Name="张乐"的记录中的Name改为"zhangle"
        sql.UpdateValues("UserInfo", new string[] { "Name" }, new string[] { "'zhangle'" }, "Name", "=", "'张乐'");

        //插入3条数据
        sql.InsertValues("UserInfo", new string[] { "3", "'王天科'", "25", "'18565789511'" });
        sql.InsertValues("UserInfo", new string[] { "4", "'赵视差'", "26", "'17745898567'" });
        sql.InsertValues("UserInfo", new string[] { "5", "'刘采集'", "27", "'13965235489'" });

        //删除Name="王天科"且Age=26的记录,DeleteValuesOR方法类似
        sql.DeleteValuesAND("UserInfo", new string[] { "Name", "Age" }, new string[] { "=", "=" }, new string[] { "'王天科'", "'26'" });

        //读取整张表
        SqliteDataReader reader = sql.ReadFullTable("UserInfo");
        while (reader.Read())
        {
            //读取ID
            Debug.Log(reader.GetInt32(reader.GetOrdinal("UniqueID")));
            //读取Name
            Debug.Log(reader.GetString(reader.GetOrdinal("Name")));
            //读取Age
            Debug.Log(reader.GetInt32(reader.GetOrdinal("Age")));
            //读取Email
            Debug.Log(reader.GetString(reader.GetOrdinal("PhoneNum")));
        }

        //读取数据表中Age>=25的所有记录的ID和Name
        reader = sql.ReadTable("UserInfo", new string[] { "UniqueID", "Name" }, new string[] { "Age" }, new string[] { ">=" }, new string[] { "'25'" });
        while (reader.Read())
        {
            //读取ID
            Debug.Log(reader.GetInt32(reader.GetOrdinal("UniqueID")));
            //读取Name
            Debug.Log(reader.GetString(reader.GetOrdinal("Name")));
        }

        //自定义SQL,删除数据表中所有Name="王天科"的记录
        sql.ExecuteQuery("DELETE FROM table1 WHERE NAME='王天科'");

        //关闭数据库连接
        sql.CloseConnection();
    }
}

Unity3D开发之SQLite本地数据库_第1张图片


欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群

你可能感兴趣的:(工具插件类)