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

相关推荐
心灵宝贝1 小时前
Mac Unity 2018.dmg游戏工具 安装步骤 简单易懂教程(附安装包)
macos·unity·游戏引擎
TO_ZRG2 小时前
Unity SDK 通过 Registry 分发及第三方依赖处理指南
unity·游戏引擎
c***42103 小时前
Django视图与URLs路由详解
数据库·django·sqlite
2***65633 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
7***n757 小时前
C++在游戏中的Cocos2d-x
游戏·游戏引擎·cocos2d
a***13149 小时前
vscode配置django环境并创建django项目(全图文操作)
vscode·django·sqlite
龙智DevSecOps解决方案13 小时前
Perforce《2025游戏技术现状报告》Part 1:游戏引擎技术的广泛影响以及生成式AI的成熟之路
人工智能·unity·游戏引擎·游戏开发·perforce
AI2中文网16 小时前
AppInventor2 使用 SQLite(三)带条件过滤查询表数据
数据库·sql·sqlite·select·app inventor 2·appinventor·tableview
Y***K43421 小时前
C在游戏中的Godot
游戏·游戏引擎·godot
Austindatabases1 天前
基于SQLite如何设计应用程序,拆散,散,还的散!
数据库·sqlite