您的位置:首页 > 移动开发 > Unity3D

【Unity】SQLite发布到Android端遇到的那些坑

2017-01-18 17:26 381 查看
发布到Android端需要添加libsqlite3.so文件,和相应的

Mono.Data.Sqlite.dll、sqlite3.dll、System.Data.dll类库

注意:所有文件放到Plugins文件夹下,libsqlite3.so放在Android文件夹下

*在Player Setting里的(安卓选项中) OtherSettings里有个Optimization 下边的API Compatbility Level 选择.NET 2.0(否则会出现System.Data.dll打包失败的情况,至于为什么,我也不知道,没研究过,从国外大神那里得知的...)

using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using UnityEngine.UI;
using System.IO;

public class AndroidLoadData : MonoBehaviour {

private Text name;
private Text score;

// Use this for initialization
void Start () {
name = GameObject.Find ("name").GetComponent<Text> ();
score = GameObject.Find ("score").GetComponent<Text> ();
ConnectionDataBase ();
}

public void ConnectionDataBase()
{
// 【沙盒路径】
string sandboxPath = Application.persistentDataPath + "/Data0118.sqlite";

// 【用于www下载数据库的路径】表示的就是unity工程中StreamingAssets中的数据库文件
// 打包成APK安装包之后,就是下面的地址
string downPath = "jar:file://" + Application.dataPath + "!/assets" + "/Data0118.sqlite";

// 【安卓端】判断沙盒路径是否存在数据库文件
// 如果不存在,就从StreamingAssets文件夹中下载数据库
if (!File.Exists(sandboxPath)) {

Debug.Log ("执行到此,表示沙盒路径中不存在 Data0118.sqlite 文件");

// 不存在数据库文件的时候,有两种创建方式
// 1.使用sqlite代码,手动创建,如果数据量过大,不适合代码的书写
// 2.通过下载的方式,去其他的目录下载,然后保存到沙盒路径

WWW www = new WWW (downPath);

// 如果数据没有下载完成,就不能继续执行后面的代码
while (!www.isDone) {

}
// 将www下载得到的所有数据,都保存到sandboxPath目录下
File.WriteAllBytes (sandboxPath, www.bytes);
}

// 链接沙盒路径中的数据库文件
string dataSandboxPath = "URI = file:" + Application.persistentDataPath + "/Data0118.sqlite";
SqliteConnection con = new SqliteConnection (dataSandboxPath);

// 打开数据库
con.Open ();

// 创建数据库命令
SqliteCommand com = con.CreateCommand ();

// 数据库命令的具体内容
com.CommandText = "select name from MyTable where name = 'XiXi'";

// 执行数据库命令
name.text = com.ExecuteScalar ().ToString();

// 给数据库命令赋值
com.CommandText = "select score from MyTable where name = 'XiXi'";

// 执行数据库命令
score.text = com.ExecuteScalar ().ToString ();

// 关闭数据库
con.Close ();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: