Unity中使用Sqlite存储本地数据

sqlite-net
sqlite下载页

我的环境:win11、unity团结1.3.4

1.下载sqlite-net,将SQLite.cs 脚本导入Unity

2.下载各平台依赖项,如dll、aar 等。导入Unity并设置

3.简单列子,打包测试

csharp 复制代码
using System;
using System.IO;
using SQLite;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public string databaseFile = "sqlite.db";

    public void Start()
    {
#if UNITY_EDITOR
        string path = Path.Combine(Directory.GetParent(Application.dataPath).FullName, databaseFile);
#elif UNITY_ANDROID
        string path = Path.Combine(Application.persistentDataPath, databaseFile);
#elif UNITY_IOS
        string path = Path.Combine(Application.persistentDataPath, databaseFile);
#else
        string path = Path.Combine(Application.dataPath, databaseFile);
#endif
        Debug.Log(path);

        // 创建数据库连接
        //SQLiteConnection第二个参数配置日期格式,默认Ticks
        var db = new SQLiteConnection(path, false);
        //打印sql语句
        db.Trace = true;
        db.Tracer = (sql) => UnityEngine.Debug.Log(sql);

        //创建表
        db.CreateTable<Users>();

        // 插入
        var user = new Users() { Name = "张三", Created = DateTime.Now };
        var user2 = new Users() { Name = "李四", Created = DateTime.Now };
        db.Insert(user);
        db.Insert(user2);
        // 查询
        var users = db.Table<Users>().Where(u => u.Name.StartsWith("张")).ToList();
        for (int i = 0; i < users.Count; i++)
        {
            Debug.Log(users[i]);
        }
    }
}

public class Users
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }

    public DateTime Created { get; set; }
    public bool IsDeleted { get; set; }

    public override string ToString()
    {
        return $"Id:{Id} 名字:{Name} 创建时间:{Created} 是否删除:{IsDeleted}";
    }
}

4.效果图,可以看到可以正常在pc/安卓上运行。


百度网盘 Unityt Sqlite测试工程

提取码:dq4n

其它参考:
https://github.com/praeclarum/sqlite-net/issues/1023
https://docs.unity3d.com/2022.1/Documentation/Manual/NativePlugins.html

相关推荐
虾球xz4 小时前
游戏引擎学习第210天
学习·游戏引擎
维度攻城狮6 小时前
高效创建工作流,可实现类似unreal engine的蓝图效果,内部使用多线程高效执行节点函数
python·游戏引擎·开源软件·虚幻·graph·工作流
浅陌sss8 小时前
设计模式 --- 原型模式
unity·游戏引擎
sensor_WU9 小时前
SQLite 中日期型数据定义及处理(Delphi 版本)
数据库·sqlite
m0_687914639 小时前
mysql和sqlite关于data数据的识别问题
数据库·mysql·sqlite
9 小时前
Unity中基于2.5D的碰撞系统
unity·游戏引擎
scott.cgi11 小时前
「Unity3D」TextMeshPro中的TMP_InputField,用来实现输入框的几个小问题
unity·ugui·textmeshpro·tmp_inputfield·inputfield·inputfield输入框·ugui输入框
虾球xz12 小时前
游戏引擎学习第212天
c++·学习·游戏引擎
我想回家种地16 小时前
sqlite3基本语句
数据库·sqlite
MarkHD16 小时前
第十一天 - MySQL/SQLite操作 - 数据库备份脚本 - 练习:监控数据存储系统
数据库·mysql·sqlite