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

相关推荐
钱彬 (Qian Bin)6 小时前
FastAPI的Alembic踩坑记录:缺失历史迁移脚本如何保留数据重建版本控制
sqlite·fastapi·数据库迁移·alembic
淡海水17 小时前
【节点】[EvaluateTipThickness节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·evaluate·thickness
小贺儿开发1 天前
Unity3D 木胎雕刻
科技·unity·人机交互·互动·雕刻
qq_454245031 天前
GraphMindStudio 数据操作层解析:基于 SQLite 的封装与自动化存储
sqlite·c#
HY小海1 天前
【Unity游戏创作】常见的设计模式
unity·设计模式·c#·游戏程序
喵手1 天前
Python爬虫实战:Boss直聘职位数据采集实战 - Playwright + 结构化解析完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·playwright·boss直聘职位数据采集·结构化解析
GDAL2 天前
SQLite 的适用场景与选型指南:它不是轻量 MySQL,而是「文件的升级版」
数据库·mysql·sqlite
布局呆星2 天前
Python 入门:FastAPI + SQLite3 + Requests 基础教学
python·sqlite·fastapi
GDAL2 天前
SQLite 核心特性与应用实战教程:轻量却不简单的嵌入式数据库
数据库·sqlite
淡海水3 天前
【节点】[EvaluateSimulationAdditionalData节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·simulation·evaluate