【千锋合集】史上最全Unity3D全套教程|匠心之作_哔哩哔哩_bilibili
1.将DLL导入工程Pulgins文件夹
Mono.Data.Sqlite D:\myUnity\Editor\Data\Mono\lib\mono\2.0
System.Data D:\myUnity\Editor\Data\Mono\lib\mono\2.0
Sqlite3 https://www.sqlite.org/download.html
1.将DLL导入工程Pulgins文件夹
Mono.Data.Sqlite D:\myUnity\Editor\Data\Mono\lib\mono\2.0
System.Data D:\myUnity\Editor\Data\Mono\lib\mono\2.0
Sqlite3 https://www.sqlite.org/download.html
2.using Mono.Data.Sqlite
引入命名空间
3.创建路径(流路径)---固定写法”Data Source=“+路径
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;//引入命名空间
public class SQLOperation : MonoBehaviour {
private void Awake()
{
//当前工程下的Assets文件夹[仅限编辑器中使用]
Debug.Log(Application.dataPath);
//流路径[各个平台均可使用]
Debug.Log(Application.streamingAssetsPath);
//沙盒路径[持久化路径][各个平台均可使用]
Debug.Log(Application.persistentDataPath);}
//数据库访问路径
private string dataBasePath;
//数据库连接对象
private SqliteConnection con;
//数据库指令对象
private SqliteCommand command;
//数据库读取对象
private SqliteDataReader reader;
private void Start()
{
#if UNITY_EDITOR
dataBasePath = "Data Source = " + Application.streamingAssetsPath + "/StudentsDataBase.sqlite";
#endif
//如果运行在Windows[exe]
#if UNITY_STANDALONE_WIN
dataBasePath = "Data Source = " + Application.streamingAssetsPath + "/StudentsDataBase.sqlite";
#endif
//实例化数据库连接对象,并绑定数据库路径链接
con = new SqliteConnection(dataBasePath);
//打开连接
con.Open();
//创建数据库指令对象
command = con.CreateCommand();
//赋值SQL语句
command.CommandText = "Select Name From StudentBaseMsgTable";
//执行SQL语句
object val=command.ExecuteScalar();
//SQL语句执行的三种方法
//执行SQL,返回受影响的行数
//赋值SQL语言
command.CommandText = "Insert Into StudentBaseMsgTable Values (3,'Rice',22,'M')";
//用于执行【增删改】的SQL语句
int rows=command.ExecuteNonQuery();
Debug.Log("受影响的行数:"+rows);
//打印执行SQL语句后的结果
Debug.Log(val);
//赋值SQL语句
command.CommandText = "Select Age From StudentBaseMsgTable where Name='Rice'";
//执行SQL,返回查询到的第一行第一列的数据结果
//用于执行【查询单个数据】的SQL语句
object age=command.ExecuteScalar();
Debug.Log(age);
//赋值SQL语句
command.CommandText = "Select * From StudentBaseMsgTable";
//执行SQL语句,返回查询后的结果【SqliteDataReader】
//用于执行【查询多个数据】的SQL语句
reader =command.ExecuteReader();
//读取下一行,若没有下一行,则返回false;
//打印结果一共有多少列
Debug.Log(reader.FieldCount);
//声明一个临时字符串
string currentColumn = "";
for (int i = 0; i < reader.FieldCount; i++)
{
currentColumn += reader.GetName(i).ToString();
currentColumn += "\t";
}
Debug.Log(currentColumn);
while (reader.Read()) {
currentColumn = "";
for (int i = 0; i < reader.FieldCount; i++) {
currentColumn+=reader.GetValue(i).ToString();
currentColumn += "\t";
}
//打印该列所有数据
Debug.Log(currentColumn);//object result = reader.GetValue(1);
//打印结果
//Debug.Log(result);}
}
/// <summary>
/// 应用程序关闭时调用一次
/// </summary>
private void OnApplicationQuit()
{if (reader != null) {
reader.Close();
reader = null;
}
if (command != null) {
command.Dispose();
command = null;
}
if (con != null) {
//关闭连接,一定要关闭
con.Close();
}
}
}