在Unity中使用SQLite数据库需要先导入三个dll文件,mono.data.sqlite.dll,System.data.dll,sqlite3.dll,到Assets/Plugins文件夹中。
mono.data.sqlite.dll和System.data.dll在Unity\Editor\Data\MonoBleedingEdge\lib\mono\2.0
sqlite3.dll需要下载:https://www.sqlite.org/download.html
window电脑下载:Precompiled Binaries for Windows(注意32位和64位);
using Mono.Data.Sqlite;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DBManager : MonoBehaviour
{
private static DBManager _dbInstance = null;
public static DBManager _DBInstance()
{
return _dbInstance;
}
private string dbName = "data"; //数据库名称
//建立数据库连接
SqliteConnection connection;
//数据库命令
SqliteCommand command;
//数据库阅读器
SqliteDataReader reader;
private void Awake()
{
//连接数据库
OpenConnect();
}
private void OnDestroy()
{
//断开数据库连接
CloseDB();
}
void Start()
{
////创建表
//string[] colNames = new string[] { "name", "password" };
//string[] colTypes = new string[] { "string", "string" };
//CreateTable("user", colNames, colTypes);
////使用泛型创建数据表
//CreateTable();
////根据条件查找特定的字段
//foreach (var item in SelectData("user", new string[] { "name" }, new string[] { "password", "123456" }))
//{
// Debug.Log(item);
//}
////更新数据
//UpdataData("user", new string[] {"name", "yyy"}, new string[] { "name" ,"wxy" });
////删除数据
//DeleteValues("user", new string[] { "name","wxyqq" });
////查询数据
//foreach (var item in GetDataBySqlQuery("T4", new string[] { "name" }))
//{
// Debug.Log(item);
//}
////foreach (var item in GetDataBySqlQuery("user",new string[] { "name"}))
////{
//// Debug.Log(item);
////}
////插入数据
//string[] values = new string[] { "3", "33", "333" };
//InsertValues("T4", values);
////使用泛型插入对象
//T4 t = new T4(2, "22", "222");
//Insert(t);
}
///
/// 删除表
///
///
///
public SqliteDataReader DeleteTable(string tableName)
{
string sql = "DROP TABLE " + tableName;
return ExecuteQuery(sql);
}
///
/// 查询整张表的数据
///
///
///
public SqliteDataReader SelectFullTableData(string tableName)
{
string queryString = "select * from " + tableName;
return ExecuteQuery(queryString);
}
///
/// 查询数据
///
/// 表名
/// 需要查找数据
///
public List GetDataBySqlQuery(string tableName, string[] fields)
{
//string queryString = "select " + fields[0];
//for (int i = 1; i < fields.Length; i++)
//{
// queryString += " , " + fields[i];
//}
//queryString += " from " + tableName;
//return ExecuteQuery(queryString);
List list = new List();
string queryString = "SELECT * FROM " + tableName;
reader = ExecuteQuery(queryString);
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
object obj = reader.GetValue(i);
list.Add(obj.ToString());
}
}
return list;
}
///
/// 查询数据
///
/// 数据表名
/// 需要查询的数据
/// 查询的条件
///
public SqliteDataReader SelectData(string tableName, string[] values, string[] fields)
{
string sql = "select " + values[0];
for (int i = 1; i < values.Length; i++)
{
sql += " , " + values[i];
}
sql += " from " + tableName + " where( ";
for (int i = 0; i < fields.Length -1 ; i += 2)
{
sql += fields[i] + " =' " + fields[i + 1] + " 'and ";
}
sql = sql.Substring(0, sql.Length - 4) + ");";
return ExecuteQuery(sql);
//用于查看打印
//List list = new List();
//reader = ExecuteQuery(sql);
//for (int i = 0; i < reader.FieldCount; i++)
//{
// object obj = reader.GetValue(i);
// list.Add(obj.ToString());
//}
//return list;
}
///
/// 执行SQL命令
///
/// SQL命令字符串
///
public SqliteDataReader ExecuteQuery(string queryString)
{
command = connection.CreateCommand();
command.CommandText = queryString;
reader = command.ExecuteReader();
return reader;
}
///
/// 创建表(使用泛型)
///
///
public void CreateTable()
{
var type = typeof(T);
string sql = "create Table " + type.Name + "( ";
var fields = type.GetFields();
for (int i = 0; i < fields.Length; i++)
{
sql += " [ " + fields[i].Name + "] " + CS2DB(fields[i].FieldType) + ",";
}
sql = sql.TrimEnd(',') + ")";
ExecuteQuery(sql);
}
///
/// CS转化为DB类别
///
/// c#中字段的类别
///
string CS2DB(Type type)
{
string result = "Text";
if (type == typeof(Int32))
{
result = "Int";
}
else if (type == typeof(String))
{
result = "Text";
}
else if (type == typeof(Single))
{
result = "FLOAT";
}
else if (type == typeof(Boolean))
{
result = "Bool";
}
return result;
}
///
/// 创建数据库
///
/// 数据库名
/// 字段名
/// 字段名类型
///
public SqliteDataReader CreateTable(string tableName, string[] colNames, string[] colTypes)
{
string queryString = "create table " + tableName + "(" + colNames[0] + " " + colTypes[0];
for (int i = 1; i < colNames.Length; i++)
{
queryString += ", " + colNames[i] + " " + colTypes[i];
}
queryString += " )";
Debug.Log("添加成功");
return ExecuteQuery(queryString);
}
///
/// 向指定数据表中插入数据
///
///
///
///
public SqliteDataReader InsertValues(string tableName, string[] values)
{
string sql = "INSERT INTO " + tableName + " values (";
foreach (var item in values)
{
sql += "'" + item + "',";
}
sql = sql.TrimEnd(',') + ")";
Debug.Log("插入成功");
return ExecuteQuery(sql);
}
///
/// 插入数据
///
///
///
///
public SqliteDataReader Insert(T t)
{
var type = typeof(T);
var fields = type.GetFields();
string sql = "INSERT INTO " + type.Name + " values (";
foreach (var field in fields)
{
//通过反射得到对象的值
sql += "'" + type.GetField(field.Name).GetValue(t) + "',";
}
sql = sql.TrimEnd(',') + ");";
Debug.Log("插入成功");
return ExecuteQuery(sql);
}
///
/// 更新数据
///
///
/// 需要修改的数据
/// 修改的条件
///
public SqliteDataReader UpdataData(string tableName, string[] values, string[] conditions)
{
string sql = "update " + tableName + " set ";
for (int i = 0; i < values.Length - 1; i += 2)
{
sql += values[i] + "='" + values[i + 1] + "',";
}
sql = sql.TrimEnd(',') + " where (";
for (int i = 0; i < conditions.Length - 1; i += 2)
{
sql += conditions[i] + "='" + conditions[i + 1] + "' and ";
}
sql = sql.Substring(0, sql.Length - 4) + ");";
Debug.Log("更新成功");
return ExecuteQuery(sql);
}
///
/// 删除数据
///
///
/// 查询条件
///
public SqliteDataReader DeleteValues(string tableName, string[] conditions)
{
string sql = "delete from " + tableName + " where (";
for (int i = 0; i < conditions.Length - 1; i += 2)
{
sql += conditions[i] + "='" + conditions[i + 1] + "' and ";
}
sql = sql.Substring(0, sql.Length - 4) + ");";
return ExecuteQuery(sql);
}
//打开数据库
public void OpenConnect()
{
try
{
//数据库存放在 Asset/StreamingAssets
string path = Application.streamingAssetsPath + "/" + dbName + ".db";
//新建数据库连接
connection = new SqliteConnection(@"Data Source = " + path);
//打开数据库
connection.Open();
Debug.Log("打开数据库");
}
catch (Exception ex)
{
Debug.Log(ex.ToString());
}
}
//关闭数据库
public void CloseDB()
{
if (command != null)
{
command.Cancel();
}
command = null;
if (reader != null)
{
reader.Close();
}
reader = null;
if (connection != null)
{
//connection.Close();
}
connection = null;
Debug.Log("关闭数据库");
}
}