当前位置:   article > 正文

unity sqlite数据库操作

unity sqlite数据库

首先在项目中添加两个动态链接库Mono.Data.Sqlite.dll和System.Data.dll

创建数据库管理脚本,该脚本用来直接操作数据库的操作,可以看作是对数据库操作的sql语句的封装。

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

public class DbAccess

{

    private SqliteConnection dbConnection;

    private SqliteCommand dbCommand;

    private SqliteDataReader reader;

    public DbAccess (string connectionString)

    {

        OpenDB (connectionString);

    }
    public DbAccess ()
    {

    }

    /// <summary>
    /// 打开数据库
    /// </summary>
    /// <param name="connectionString">Connection string.</param>
    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);
        }

    }

    /// <summary>
    /// 关闭数据库
    /// </summary>
    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.");

    }

    /// <summary>
    /// 执行sql语句
    /// </summary>
    /// <returns>The query.</returns>
    /// <param name="sqlQuery">查询语句.</param>
    public SqliteDataReader ExecuteQuery (string sqlQuery)

    {

        Debug.Log ("sql="+sqlQuery);
        dbCommand = dbConnection.CreateCommand ();

        dbCommand.CommandText = sqlQuery;

        reader = dbCommand.ExecuteReader ();

        return reader;

    }

    /// <summary>
    /// 查询整个table的数据
    /// </summary>
    /// <returns>The full table.</returns>
    /// <param name="tableName">表名.</param>
    public SqliteDataReader ReadFullTable (string tableName)

    {

        string query = "SELECT * FROM " + tableName;

        return ExecuteQuery (query);

    }

    /// <summary>
    /// 插入数据
    /// </summary>
    /// <returns>The into.</returns>
    /// <param name="tableName">表名</param>
    /// <param name="values">需要插入的字段内容,注意字符串需要添加单引号 如 ‘name’</param>
    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);

    }

    /// <summary>
    /// 更新table内容
    /// </summary>
    /// <returns>The into.</returns>
    /// <param name="tableName">Table 名称.</param>
    /// <param name="cols">需要更新的字段名称数组.</param>
    /// <param name="colsvalues">需要更新的字段对应的值.</param>
    /// <param name="selectkey">更新依据的字段.</param>
    /// <param name="selectvalue">更新依据字段对应的值</param>
    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);
    }

    /// <summary>
    /// 根据删除条件,删除对应的数据
    /// </summary>
    /// <param name="tableName">Table 名称.</param>
    /// <param name="cols">字段数组.</param>
    /// <param name="colsvalues">字段数组对应的值.</param>
    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);
    }

    /// <summary>
    /// 插入数据,只插入部分字段的数据
    /// </summary>
    /// <returns>The into specific.</returns>
    /// <param name="tableName">Table 名称.</param>
    /// <param name="cols">需要插入的字段数组.</param>
    /// <param name="values">需要插入的字段数组对应的值.</param>
    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);

    }
    /// <summary>
    /// 根据表名,删除该表的全部数据
    /// </summary>
    /// <returns>The contents.</returns>
    /// <param name="tableName">Table name.</param>
    public SqliteDataReader DeleteContents (string tableName)

    {

        string query = "DELETE FROM " + tableName;

        return ExecuteQuery (query);

    }

    /// <summary>
    /// 创建一个数据表
    /// </summary>
    /// <returns>The table.</returns>
    /// <param name="name">Name.</param>
    /// <param name="col">Col.</param>
    /// <param name="colType">Col type.</param>
    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);

    }

    /// <summary>
    /// 根据条件筛选数据
    /// </summary>
    /// <returns>The where.</returns>
    /// <param name="tableName">Table name.</param>
    /// <param name="items">需要筛选的字段.</param>
    /// <param name="col">筛选条件的健.</param>
    /// <param name="operation">筛选符号,如 >,<,= </param>.</param>
    /// <param name="values">筛选条件的值.</param>
    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);

    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312

调用数据库方法,将该脚本挂载到场景中,完成对数据库管理脚本封装方法的调用。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;
public class SqliteTest1 : MonoBehaviour {
    string dbPath;
    string dbName;
    DbAccess db;
    // Use this for initialization
    void Start () {
        dbName="userInfo.db";
        dbPath=getPath ();
        if (!System.IO.File.Exists (dbPath)) {
            //创建数据库
            db = new DbAccess ("data source=" + dbPath);
            //创建数据库表,与字段
            SqliteDataReader reader= db.CreateTable ("user", new string[]{ "name", "age", "sex", "adress" }, new string[]{ "text", "integer", "text", "text" });
            if (reader != null)
                Debug.Log ("create tabel success");
            else
                Debug.LogError ("create tabel fail");
        } else db = new DbAccess ("data source=" + dbPath);





        //关闭对象
        //db.CloseSqlConnection();
    }



    string getPath(){
        string path=Application.dataPath+"/"+dbName;
        #if UNITY_EDITOR
        path=Application.streamingAssetsPath+"/"+dbName;
        if (!System.IO.Directory.Exists (path)){
//          System.IO.DirectoryInfo dir=new System.IO.DirectoryInfo(Application.streamingAssetsPath);
//          dir.Create();

            System.IO.Directory.CreateDirectory(Application.streamingAssetsPath);
        }


        #elif UNITY_ANDROID
        path=Application.persistentDataPath+"/"+dbName;
        #elif UNITY_IOS
        path=Application.persistentDataPath+"/"+dbName;
        #endif

        Debug.Log (Application.dataPath);
        Debug.Log (Application.persistentDataPath);
        Debug.Log (Application.temporaryCachePath);
        Debug.Log (path);
        return path;
    }


    void OnDestroy(){
        Debug.Log ("<color=#00ff00>close database</color>");
        //关闭对象
        db.CloseSqlConnection();
    }

    void InsertData(){

        db.InsertInto ("user", new string[]{ "'zhangsan'","11","'man'","'beijing'"});
        db.InsertInto ("user", new string[]{ "'lisi'","11","'woman'","'huoying'"});

    }

        void UpdateData(){
            db.UpdateInto ("user",new string[]{ "age", "sex"}, new string[]{ "82", "'woman'"  },"name","'zhangsan'");
        }

        void DeleteData(){
            db.Delete ("user",new string[]{ "age", "sex"}, new string[]{ "82", "'woman'"  });
    }

        void QueryData(){
            string query = "select * from user where name='zhangsan'";
            SqliteDataReader reader=db.ExecuteQuery (query);
            while(reader.Read()){
                Debug.Log ("name="+reader["name"]);
                Debug.Log ("age="+reader["age"]);
                Debug.Log ("sex="+reader["sex"]);
                Debug.Log ("adress="+reader["adress"]);

            }
        }

        void SelectData(){

        // "select (name,age,sex) from user where age > 20";
        SqliteDataReader reader= db.SelectWhere ("user",new string[]{"name","age","sex"},new string[]{"age"},new string[]{">"},new string[]{"20"});
        while(reader.Read()){
            Debug.Log ("name="+reader["name"]);
            Debug.Log ("age="+reader["age"]);
            Debug.Log ("sex="+reader["sex"]);

        }
        }


        void OnGUI() {

        if (GUI.Button (new Rect (10, 20, 100, 40), "insert data")) {

            InsertData ();


        } else if (GUI.Button (new Rect (10, 80, 100, 40), "delete data")) {

            DeleteData ();



        } else if (GUI.Button (new Rect (10, 120, 100, 40), "updata data")) {

            UpdateData ();




        } else if (GUI.Button (new Rect (10, 180, 100, 40), "query data")) {

            QueryData ();




        } else if (GUI.Button (new Rect (10, 250, 100, 40), "select data")) {

            SelectData ();


        }  
        else if (GUI.Button (new Rect (180, 20, 100, 40), "query all data")) {

        SqliteDataReader reader=    db.ReadFullTable("user");
            int count = 0;
        while(reader.Read()){
                count++;
//          Debug.Log ("name="+reader["name"]);
//          Debug.Log ("age="+reader["age"]);
//          Debug.Log ("sex="+reader["sex"]);
//          Debug.Log ("adress="+reader["adress"]);
            Debug.Log ("name=" + reader ["name"] + ",age=" + reader ["age"] + ",sex=" + reader ["sex"] + ",adress=" + reader ["adress"]);
        }
        Debug.Log ("count="+count);

        }  

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157

资源导包时报错:ArgumentException: The Assembly System.Configuration is referenced by System.Data (‘Assets/plugins/System.Data.dll’). But the dll is not allowed to be included or could not be found.
这里写图片描述

解决方法:在PlaySettings--other setting 中修改Api Compatibility Level 改成.NET 2.0

demo 下载:http://download.csdn.net/detail/u011484013/9705852

下载内容是一个unity资源包,拖到项目中之后,创建一个空场景,把SqliteTest1.cs挂载到相机上面,就可以运行测试。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/127147?site
推荐阅读
相关标签
  

闽ICP备14008679号