一:准备,Mono.Data.Sqlite.dll,System.Data.dll,sqlite3.dll(X86和X86_64),这些dll文件是必须的。将他们放到Plugins文件夹下即可。dll缺一不可,否则打包出来会有问题。然后需要将API Compatibility Level切换到.NET 2.0 。
二:在网上找了一个连接和读取的脚本:
using UnityEngine;
using System.Data;
using System;
using System.Collections;
using Mono.Data.Sqlite;
public class DbAccess
{
private SqliteConnection dbConnection;
private SqliteCommand dbCommand;
private SqliteDataReader reader;
public DbAccess (string connectionString)
{
OpenDB (connectionString);
}
public DbAccess ()
{
}
///
/// 打开数据库
///
/// Connection string.
public void OpenDB (string connectionString)
{
try
{
dbConnection = new SqliteConnection (connectionString);
dbConnection.Open ();
Debug.Log ("Connected to db");
}
catch(Exception e)
{
string temp1 = e.ToString();
Debug.Log(temp1);
}
}
///
/// 关闭数据库
///
public void CloseSqlConnection ()
{
if (dbCommand != null) {
dbCommand.Dispose ();
}
dbCommand = null;
if (reader != null) {
reader.Dispose ();
}
reader = null;
if (dbConnection != null) {
dbConnection.Close ();
}
dbConnection = null;
Debug.Log ("Disconnected from db.");
}
///
/// 执行sql语句
///
///
/// 查询语句.
public SqliteDataReader ExecuteQuery (string sqlQuery)
{
Debug.Log ("sql="+sqlQuery);
dbCommand = dbConnection.CreateCommand ();
dbCommand.CommandText = sqlQuery;
reader = dbCommand.ExecuteReader ();
return reader;
}
///
/// 查询整个table的数据
///
///
/// 表名.
public SqliteDataReader ReadFullTable (string tableName)
{
string query = "SELECT * FROM " + tableName;
return ExecuteQuery (query);
}
///
/// 插入数据
///
///
/// 表名
/// 需要插入的字段内容,注意字符串需要添加单引号 如 ‘name’
public SqliteDataReader InsertInto (string tableName, string[] values)
{
string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
for (int i = 1; i < values.Length; ++i) {
query += ", " + values[i];
}
query += ")";
return ExecuteQuery (query);
}
///
/// 更新table内容
///
///
/// Table 名称.
/// 需要更新的字段名称数组.
/// 需要更新的字段对应的值.
/// 更新依据的字段.
/// 更新依据字段对应的值
public SqliteDataReader UpdateInto (string tableName, string []cols,string []colsvalues,string selectkey,string selectvalue)
{
string query = "UPDATE "+tableName+" SET "+cols[0]+" = "+colsvalues[0];
for (int i = 1; i < colsvalues.Length; ++i) {
query += ", " +cols[i]+" ="+ colsvalues[i];
}
query += " WHERE "+selectkey+" = "+selectvalue+" ";
return ExecuteQuery (query);
}
///
/// 根据删除条件,删除对应的数据
///
/// Table 名称.
/// 字段数组.
/// 字段数组对应的值.
public SqliteDataReader Delete(string tableName,string []cols,string []colsvalues)
{
string query = "DELETE FROM "+tableName + " WHERE " +cols[0] +" = " + colsvalues[0];
for (int i = 1; i < colsvalues.Length; ++i) {
query += " or " +cols[i]+" = "+ colsvalues[i];
}
return ExecuteQuery (query);
}
///
/// 插入数据,只插入部分字段的数据
///
///
/// Table 名称.
/// 需要插入的字段数组.
/// 需要插入的字段数组对应的值.
public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)
{
if (cols.Length != values.Length) {
throw new SqliteException ("columns.Length != values.Length");
}
string query = "INSERT INTO " + tableName + "(" + cols[0];
for (int i = 1; i < cols.Length; ++i) {
query += ", " + cols[i];
}
query += ") VALUES (" + values[0];
for (int i = 1; i < values.Length; ++i) {
query += ", " + values[i];
}
query += ")";
return ExecuteQuery (query);
}
///
/// 根据表名,删除该表的全部数据
///
///
/// Table name.
public SqliteDataReader DeleteContents (string tableName)
{
string query = "DELETE FROM " + tableName;
return ExecuteQuery (query);
}
///
/// 创建一个数据表
///
///
/// Name.
/// Col.
/// Col type.
public SqliteDataReader CreateTable (string name, string[] col, string[] colType)
{
if (col.Length != colType.Length) {
throw new SqliteException ("columns.Length != colType.Length");
}
string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
for (int i = 1; i < col.Length; ++i) {
query += ", " + col[i] + " " + colType[i];
}
query += ")";
return ExecuteQuery (query);
}
///
/// 根据条件筛选数据
///
///
/// Table name.
/// 需要筛选的字段.
/// 筛选条件的健.
/// 筛选符号,如 >,<,= .
/// 筛选条件的值.
public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)
{
if (col.Length != operation.Length || operation.Length != values.Length) {
throw new SqliteException ("col.Length != operation.Length != values.Length");
}
string query = "SELECT " + items[0];
for (int i = 1; i < items.Length; ++i) {
query += ", " + items[i];
}
query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
for (int i = 1; i < col.Length; ++i) {
query += " AND " + col[i] + operation[i] + "'" + values[0] + "' ";
}
return ExecuteQuery (query);
}
}
三:然后将sqlite的数据放到了StreamingAsset文件下,然后程序一启动,会将数据拷到PersistentPath目录下,防止文件丢失。
当连接数据库的时候,会从工程目录下找这个文件,如果没有就会从沙盒路径下拷过来,然后进去读取。因为sqlite文件是db结尾的,所以不能用Resources加载。 部分代码如下
void Awake(){
CopyFile(Application.streamingAssetsPath + dbName, Application.persistentDataPath + dbName);
}
///
/// 拷贝文件
///
///
///
private void CopyFile(string sourcePath,string distPath) {
if (!System.IO.File.Exists(distPath)){
if (System.IO.File.Exists(sourcePath)) {
System.IO.File.Copy(sourcePath, distPath);
}
}
}
///
/// 连接数据库,请进行读取数据
///
private void ConnectSqllite() {
dbPath = getPath();
if (!System.IO.File.Exists(dbPath)) {
CopyFile(Application.persistentDataPath + dbName, dbPath);
if (!System.IO.File.Exists(dbPath)) {
JT_MessageBox.ShowMessageBox(MessageBoxStyle.OnlyOK, "提示消息", "读取配置文件失败(配置文件丢失或损坏,请联系管理员)");
return;
}
db = new DbAccess("data source=" + dbPath);
}
else {
db = new DbAccess("data source=" + dbPath);
}
QueryAllData();
db.CloseSqlConnection();
}
///
/// 读取配置文件,将数据存入 textConfigDic字典中
///
public void QueryAllData() {
SqliteDataReader reader = db.ReadFullTable("systeminfo1");
int count = 0;
while (reader.Read()) {
TextConfig tc = new TextConfig();
tc.Id = int.Parse(reader["id"].ToString());
tc.Name = reader["name"].ToString();
tc.Meno = reader["meno"].ToString();
tc.VideoURL = reader["video"].ToString();
tc.SoundURL = reader["sound"].ToString();
tc.Isvideo = int.Parse(reader["isvideo"].ToString());
tc.Createdate = reader["createdate"].ToString();
textConfigDic.Add(count, tc);
//Debug.Log ("name=" + reader ["name"] + ",age=" + reader ["age"] + ",sex=" + reader ["sex"] + ",adress=" + reader ["adress"]);
count++;
}
}
///
/// 配置文件目录
///
///
string getPath() {
string path = Application.dataPath + "/" + dbName;
return path;
}
最后打包出来就OK了。
最后总结一下:主要在于dll文件,这个花了很长时间。PC条件下,X86,X86_64两个都要要,否则,打包出来可能会有问题。其他的基本没什么。
其实我个人还是喜欢Json。可能是用的多吧,轻巧方便,虽然易读性差点。
有兴趣的可以加我的个人学习交流群(小众群,没人说话的,哈哈):195118593
下面贴几个讲使用sqlitede 我觉得比较好的文章:
https://blog.csdn.net/here4one/article/details/54934804