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

相关推荐
切韵9 天前
Unity编辑器扩展:UI绑定复制工具
ui·unity·编辑器
矿渣渣9 天前
SQLite3 在嵌入式系统中的应用指南
数据库·sqlite·嵌入式实时数据库
矿渣渣9 天前
Zynq + FreeRTOS + YAFFS2 + SQLite3 集成指南
数据库·sqlite
编程乐学(Arfan开发工程师)9 天前
73、单元测试-断言机制
服务器·数据库·servlet·单元测试·sqlite·log4j·mybatis
mxpan10 天前
深入探究 Go 语言中使用 SQLite 数据库
数据库·golang·sqlite
10 天前
Lua复习之何为闭包
开发语言·unity·游戏引擎·lua·交互
深空数字孪生10 天前
2025年小程序地图打车的5大技术革新:实时路况预测与智能调度升级
大数据·人工智能·unity·性能优化·小程序·游戏引擎
RPGMZ10 天前
RPGMZ 游戏引擎如何与lua进行互相调用 初探
开发语言·javascript·游戏引擎·lua·rpgmz
程序猿多布10 天前
Unity Addressable使用之检测更新流程
unity·addressable
fareast_mzh10 天前
Import a `.del` file (a delimited file, exported from DB2) into SQLite
数据库·sqlite