一、准备
1、我使用的是Unity2022
2、到Unity的安装目录下找Mono.Data.Sqlite.dll和System.Data.dll,具体路径在Unity\Hub\Editor\2022.3.14f1c1\Editor\Data\MonoBleedingEdge\lib\mono\2.0-api
3、sqlite3.dll文件,下载地址:SQLite Download Page
按需下载32位或者64位
至此,编辑器内可以调试,但是编译成APK的话,真机不好使,需要下载libsqlite.so文件
4、libsqlite.so我存入了百度网盘:
链接:https://pan.baidu.com/s/1S2uTZXgh1yXX5aC9n8pjTQ?pwd=g6zx
提取码:g6zx
最终工程插件如下:
二、代码
1、sql:
using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using UnityEngine;
public class SqliteHelper
{
// 单例
static SqliteHelper _instance = null;
public static SqliteHelper Instance
{
get
{
if (_instance == null)
{
_instance = new SqliteHelper();
}
return _instance;
}
}
//数据库连接
SqliteConnection m_Connection;
//数据库命令
SqliteCommand m_Command;
//数据库阅读器
SqliteDataReader m_Reader;
/// <summary>
/// 连接数据库(如果数据库不存在,会自动创建数据库)
/// </summary>
public void Connect(string path)
{
string connectString = "URI=file:" + path;
m_Connection = new SqliteConnection(connectString);
m_Connection.Open();
Debug.Log("打开数据库: " + connectString);
}
/// <summary>
/// 建表
/// </summary>
public void CreateTable()
{
string sql = "create Table Item(name Text, price FLOAT)";
ExecuteQuery(sql);
}
/// <summary>
/// 执行SQL命令
/// </summary>
/// <param name="queryString">SQL命令字符串</param>
public SqliteDataReader ExecuteQuery(string queryString)
{
m_Command = m_Connection.CreateCommand();
m_Command.CommandText = queryString;
m_Reader = m_Command.ExecuteReader();
return m_Reader;
}
/// <summary>
/// 插入数据
/// </summary>
public void Insert()
{
string sql = "INSERT INTO Item values ('苹果','39.9')";
ExecuteQuery(sql);
}
/// <summary>
/// 查询整个表
/// </summary>
public void SelectFullTable()
{
string queryString = "SELECT * FROM Item";
m_Reader = ExecuteQuery(queryString);
while (m_Reader.Read())
{
Debug.Log(m_Reader.GetValue(0).ToString());
Debug.Log(m_Reader.GetValue(1).ToString());
}
}
}
2、调用:
string path = Application.persistentDataPath + "/data.db";
SqliteHelper.Instance.Connect(path);
Debug.Log("打开数据库");
三、Player Settings:
Write Permission 设置为 External (SDCard),在手机硬盘上开启写入权限
四、真机截图:
简单做了个测试UI,手机是IQOO NEO9 PRO