欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > 【数据库】Unity 使用 Sqlite 数据库

【数据库】Unity 使用 Sqlite 数据库

2025/1/13 17:19:02 来源:https://blog.csdn.net/qq_38513810/article/details/145027693  浏览:    关键词:【数据库】Unity 使用 Sqlite 数据库

1.找到需要三个 DLL

  • Mono.Data.Sqlite.dll
  • System.Data.dll
  • sqlite3.dll

上面两个dll可在本地unity安装目录找到:

C:\Program Files\Unity\Hub\Editor\2022.3.xxf1c1\Editor\Data\MonoBleedingEdge\lib\mono\unityjit-win32

下面dll可在sqlite官网下载到:

https://www.sqlite.org/download.html

2.将以上三个dll放入unity的里面的Plugins里面

3.测试代码:

using UnityEngine;
using Mono.Data.Sqlite;
using System.Data;public class SQLiteTest : MonoBehaviour
{private string dbPath;void Start(){// SQLite 数据库的路径dbPath = "URI=file:" + Application.streamingAssetsPath + "/example.db";Debug.Log("Database Path: " + dbPath);CreateTable();InsertData("TestKey", "TestValue");string value = GetData("TestKey");Debug.Log("Retrieved Value: " + value);}private void CreateTable(){using (IDbConnection dbConnection = new SqliteConnection(dbPath)){dbConnection.Open();using (IDbCommand command = dbConnection.CreateCommand()){command.CommandText = "CREATE TABLE IF NOT EXISTS MyTable (key TEXT PRIMARY KEY, value TEXT)";command.ExecuteNonQuery();}}}private void InsertData(string key, string value){using (IDbConnection dbConnection = new SqliteConnection(dbPath)){dbConnection.Open();using (IDbCommand command = dbConnection.CreateCommand()){command.CommandText = "INSERT OR REPLACE INTO MyTable (key, value) VALUES (@key, @value)";command.Parameters.Add(new SqliteParameter("@key", key));command.Parameters.Add(new SqliteParameter("@value", value));command.ExecuteNonQuery();}}}private string GetData(string key){using (IDbConnection dbConnection = new SqliteConnection(dbPath)){dbConnection.Open();using (IDbCommand command = dbConnection.CreateCommand()){command.CommandText = "SELECT value FROM MyTable WHERE key = @key";command.Parameters.Add(new SqliteParameter("@key", key));using (IDataReader reader = command.ExecuteReader()){if (reader.Read()){return reader.GetString(0);}}}}return null;}private void Update(){if (Input.GetKeyDown(KeyCode.T)){Debug.Log("写入数据");InsertData("名字", "蜡笔小新");InsertData("年龄", "5岁");InsertData("职业", "幼儿园学生");InsertData("爱好", "大姐姐");}if (Input.GetKeyDown(KeyCode.Space)){Debug.Log(GetData("名字"));Debug.Log(GetData("年龄"));Debug.Log(GetData("职业"));Debug.Log(GetData("爱好"));}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com