zoukankan      html  css  js  c++  java
  • unity3d sqlite数据库的读写方法

      首先,我们要从unity的安装路径中复制mono.data.sqlite.dll和sqlite3.dll两个动态链接库到untiy的plugins目录下,如下图所示:

    使用navicat for sqlite创建一个sqlite数据库文件,放到Resources文件夹目录中,如下图所示:

    新建一个DbAccess脚步,添加以下脚步:

    using UnityEngine;

    using System;

    using System.Collections;

    using Mono.Data.Sqlite;

    using System.IO;

     

    public class DbAccess  {

        private SqliteConnection dbConnection;//sql连接

        private SqliteCommand dbCommand=null;//sql命令

        private SqliteDataReader dbReader;//sql读取器

     

        public DbAccess(string connectionString)

        {

            string appDBPath = "";

     

            if(Application.platform == RuntimePlatform.WindowsEditor)//如果是windows编辑器中

            {

                 appDBPath = Application.dataPath+"//"+connectionString;

            }

            else if(Application.platform == RuntimePlatform.Android)--如果是安卓平台

            {

                appDBPath = Application.persistentDataPath +"/" + connectionString;

                if (!File.Exists(appDBPath))

                {

                    WWW loader = new WWW("jar:file://" + Application.dataPath + "/" + connectionString);//把数据库复制到安卓可写路径中,注:sqlite不能在安装包中读取数据

                    File.WriteAllBytes(appDBPath,loader.bytes);

                }

            }

            OpenDB("Data Source="+appDBPath);

        }

     

        private void OpenDB(string connectionString)

        {

            try

            {

                dbConnection = new SqliteConnection(connectionString);

                dbConnection.Open();

                Debug.Log("connect to db");

            }

            catch (System.Exception ex)

            {

                Debug.Log(ex.Message);

            }

        }

     

        public void CloseSqlConnection()//关闭数据库连接

        {

            if (dbCommand!=null)

                dbCommand.Dispose();

            dbCommand = null;

     

            if (dbReader!=null)

                dbReader.Dispose();

            dbReader = null;

     

            if (dbConnection!=null)

                dbConnection.Close();

            dbConnection = null;

        }

     

        public SqliteDataReader ExecuteQuery(string sqlQuery)//执行查询

        {

            dbCommand = dbConnection.CreateCommand();

            dbCommand.CommandText = sqlQuery;

            dbReader = dbCommand.ExecuteReader();

            return dbReader;

        }

     

        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];

            }

            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 += ")";

     

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

     

        }

     

    }

    使用事例:

    数据库的Dialog表中有一下数据:

            DbAccess db = new DbAccess("/Resources/DazzleParkour.sqlite");

            using (SqliteDataReader reader = db.SelectWhere("Dialog", new string[] { "id,Name,FileName,Scale" }, new string[] { "Scale" }, new string[] { "=" }, new string[] { "1" }))//读取出Scale等于1的数据

            {

                while (reader.Read())// 循环遍历数据

                {

                    int name = reader.GetInt32(reader.GetOrdinal("id"));

                    Debug.Log(name);

                }

                reader.Close();

                db.CloseSqlConnection();

            }

    最后打印的数据如下

    在打包时,注意要把playersetting里的api解析等级改为.Net 2.0

  • 相关阅读:
    自定义View的ToolBar布局报错Error:(2) No resource identifier found for attribute 'context' in package 'c
    在学git之主分支 branch
    获取发布版SHA1
    关于开启线程与UI的操作
    播放音频和视频(VideoView控件)
    通知栏Notification的应用
    Android 真机调式 Installation failed with message 远程主机强迫关闭了一个现有的连接。. It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing. WA
    运行程序申请危险权限
    mysql乐观锁总结和实践
    Nginx配置文件nginx.conf中文详解
  • 原文地址:https://www.cnblogs.com/HemJohn/p/4850747.html
Copyright © 2011-2022 走看看