通过Unity在Android中使用填充的SQLite数据库

亚历克斯·乔利格

我将在使用创建的Android游戏中使用预填充的SQLite数据库Unity

由于这种简单的方法在Android上不起作用(它在Windows很完美),因此,我已按照本教程在Android应用中使用数据库。

public void OpenDB(string p) //p is the database name

{
    // check if file exists in Application.persistentDataPath

    string filepath = Application.persistentDataPath + "/" + p;

    if(!File.Exists(filepath))

    {

        // if it doesn't ->

        // open StreamingAssets directory and load the db -> 

        WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + p);  // this is the path to your StreamingAssets in android

        while(!loadDB.isDone) {}  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check

        // then save to Application.persistentDataPath

        File.WriteAllBytes(filepath, loadDB.bytes);

    }

    //open db connection

    connection = "URI=file:" + filepath;

    dbcon = new SqliteConnection(connection);

    dbcon.Open();

}

当我运行此代码时,出现以下错误:

SqliteSyntaxException:文件已加密或不是数据库

这是完整的错误:

SqliteSyntaxException:文件已加密或不是数据库Mono.Data.SqliteClient.SqliteCommand.GetNextStatement(IntPtr pzStart,System.IntPtr&pzTail,System.IntPtr&pStmt)Mono.Data.SqliteClient.SqliteCommand.ExecuteReader(CommandBehavior行为,布尔值旺旺,系统.Int32&rows_affected)Mono.Data.SqliteClient.SqliteCommand.ExecuteReader(CommandBehavior行为)Mono.Data.SqliteClient.SqliteCommand.ExecuteDbDataReader(CommandBehavior行为)System.Data.Common.DbCommand.ExecuteReader()System.Data.Common.DbCommand.System .Data.IDbCommand.ExecuteReader()dbAccess.SingleSelectWhere(System.String tableName,System.String itemToSelect,System.String wCol,System.String wPar,System.String wValue)(在Assets / dbAccess.cs:152)

我已经从那篇博文中下载了示例,并且遇到了同样的错误。

我对此行表示怀疑:

File.WriteAllBytes(filepath, loadDB.bytes); 

我的想法是由于某种原因,它无法将数据库数据写入文件中。

有谁知道如何解决这个问题?

亚历克斯·乔利格

感谢这个博客,我解决了这个问题

由于if语句根据应用程序在哪个平台上执行不同的行为,因此该代码在每个平台上均能完美运行。

这是DataService.cs做重要部分的(或者我最好说整个部分

using SQLite4Unity3d;
using UnityEngine;
#if !UNITY_EDITOR
using System.Collections;
using System.IO;
#endif
using System.Collections.Generic;

public class DataService  {

    private SQLiteConnection _connection;

    public DataService(string DatabaseName){

#if UNITY_EDITOR
            var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
#else
        // check if file exists in Application.persistentDataPath
        var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);

        if (!File.Exists(filepath))
        {
            Debug.Log("Database not in Persistent path");
            // if it doesn't ->
            // open StreamingAssets directory and load the db ->

#if UNITY_ANDROID 
            var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
            while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
            // then save to Application.persistentDataPath
            File.WriteAllBytes(filepath, loadDb.bytes);
#elif UNITY_IOS
                 var loadDb = Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);
#elif UNITY_WP8
                var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);

#elif UNITY_WINRT
        var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
        // then save to Application.persistentDataPath
        File.Copy(loadDb, filepath);
#else
    var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
    // then save to Application.persistentDataPath
    File.Copy(loadDb, filepath);

#endif

            Debug.Log("Database written");
        }

        var dbPath = filepath;
#endif
            _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
        Debug.Log("Final PATH: " + dbPath);     

    }

    public void CreateDB(){
        _connection.DropTable<Person> ();
        _connection.CreateTable<Person> ();

        _connection.InsertAll (new[]{
            new Person{
                Id = 1,
                Name = "Tom",
                Surname = "Perez",
                Age = 56
            },
            new Person{
                Id = 2,
                Name = "Fred",
                Surname = "Arthurson",
                Age = 16
            },
            new Person{
                Id = 3,
                Name = "John",
                Surname = "Doe",
                Age = 25
            },
            new Person{
                Id = 4,
                Name = "Roberto",
                Surname = "Huertas",
                Age = 37
            }
        });
    }

    public IEnumerable<Person> GetPersons(){
        return _connection.Table<Person>();
    }

    public IEnumerable<Person> GetPersonsNamedRoberto(){
        return _connection.Table<Person>().Where(x => x.Name == "Roberto");
    }

    public Person GetJohnny(){
        return _connection.Table<Person>().Where(x => x.Name == "Johnny").FirstOrDefault();
    }

    public Person CreatePerson(){
        var p = new Person{
                Name = "Johnny",
                Surname = "Mnemonic",
                Age = 21
        };
        _connection.Insert (p);
        return p;
    }
}

接下来是另外两个脚本来创建或使用现有数据库。

ExistingDBScript.cs

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class ExistingDBScript : MonoBehaviour {

    public Text DebugText;

    // Use this for initialization
    void Start () {
        var ds = new DataService ("existing.db");
        //ds.CreateDB ();
        var people = ds.GetPersons ();
        ToConsole (people);

        people = ds.GetPersonsNamedRoberto ();
        ToConsole("Searching for Roberto ...");
        ToConsole (people);

        ds.CreatePerson ();
        ToConsole("New person has been created");
        var p = ds.GetJohnny ();
        ToConsole(p.ToString());

    }

    private void ToConsole(IEnumerable<Person> people){
        foreach (var person in people) {
            ToConsole(person.ToString());
        }
    }

    private void ToConsole(string msg){
        DebugText.text += System.Environment.NewLine + msg;
        Debug.Log (msg);
    }

}

CreateDBScript.cs

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class CreateDBScript : MonoBehaviour {

    public Text DebugText;

    // Use this for initialization
    void Start () {
        StartSync();
    }

    private void StartSync()
    {
        var ds = new DataService("tempDatabase.db");
        ds.CreateDB();

        var people = ds.GetPersons ();
        ToConsole (people);
        people = ds.GetPersonsNamedRoberto ();
        ToConsole("Searching for Roberto ...");
        ToConsole (people); 
    }

    private void ToConsole(IEnumerable<Person> people){
        foreach (var person in people) {
            ToConsole(person.ToString());
        }
    }

    private void ToConsole(string msg){
        DebugText.text += System.Environment.NewLine + msg;
        Debug.Log (msg);
    }
}

person脚本,在数据库中显示人员表

using SQLite4Unity3d;

public class Person  {

    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }

    public override string ToString ()
    {
        return string.Format ("[Person: Id={0}, Name={1},  Surname={2}, Age={3}]", Id, Name, Surname, Age);
    }
}

另外,您还需要向git存储库中Sqlite.cs找到插件和项目。

它帮助我克服了这个问题,希望它也对其他人有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在Android Studio中使用Kotlin访问预先填充的本地sqlite数据库?

来自分类Dev

无法在Android中使用PhoneGap / Cordova访问预填充的SQLite数据库

来自分类Dev

如何填充SQLite数据库并在phonegap中使用该数据库?

来自分类Dev

通过android创建sqlite数据库

来自分类Dev

在Android的SQLite数据库中使用相同的数据库文件插入不同的表

来自分类Dev

通过SQLite数据库条目填充设置变量

来自分类Dev

通过文件或适配器填充SQLite数据库

来自分类Dev

从Android上的SQLite数据库填充ListView

来自分类Dev

从sqlite数据库填充导航菜单-Android

来自分类Dev

Android:直接从SQLite数据库填充ListView-无需使用ArrayList

来自分类Dev

使用SQLite的Android数据库错误

来自分类Dev

在预填充的 SQLite 数据库上使用 SQLCipher/Encryption

来自分类Dev

无法使用 SQLite 数据库查询填充 ListView

来自分类Dev

使用 Swift 中的 SQLite 数据库行填充 UITableView

来自分类Dev

在Android中使用SQLite数据库插入数据时出错

来自分类Dev

在Android中使用外部数据库

来自分类Dev

ListView在android中使用数据库

来自分类Dev

在android中使用本地数据库

来自分类Dev

在Android开发中使用数据库

来自分类Dev

ListView在android中使用数据库

来自分类Dev

在Realm中使用预填充的数据库

来自分类Dev

在 Rails 中使用数据库中的 JSON 填充表

来自分类Dev

使用android在SQLite数据库表中使用WHERE子句检索值

来自分类Dev

如何在Android应用程序中使用外部sqlite数据库

来自分类Dev

如何在Android中使用有关sqlite数据库的insert()方法

来自分类Dev

在Android中使用rawQuery和rowid从sqlite数据库中选择一行

来自分类Dev

尝试从SQLite数据库填充ListView

来自分类Dev

从数据库(SQLite)填充TextWatcher

来自分类Dev

从SQLite数据库填充表布局

Related 相关文章

  1. 1

    如何在Android Studio中使用Kotlin访问预先填充的本地sqlite数据库?

  2. 2

    无法在Android中使用PhoneGap / Cordova访问预填充的SQLite数据库

  3. 3

    如何填充SQLite数据库并在phonegap中使用该数据库?

  4. 4

    通过android创建sqlite数据库

  5. 5

    在Android的SQLite数据库中使用相同的数据库文件插入不同的表

  6. 6

    通过SQLite数据库条目填充设置变量

  7. 7

    通过文件或适配器填充SQLite数据库

  8. 8

    从Android上的SQLite数据库填充ListView

  9. 9

    从sqlite数据库填充导航菜单-Android

  10. 10

    Android:直接从SQLite数据库填充ListView-无需使用ArrayList

  11. 11

    使用SQLite的Android数据库错误

  12. 12

    在预填充的 SQLite 数据库上使用 SQLCipher/Encryption

  13. 13

    无法使用 SQLite 数据库查询填充 ListView

  14. 14

    使用 Swift 中的 SQLite 数据库行填充 UITableView

  15. 15

    在Android中使用SQLite数据库插入数据时出错

  16. 16

    在Android中使用外部数据库

  17. 17

    ListView在android中使用数据库

  18. 18

    在android中使用本地数据库

  19. 19

    在Android开发中使用数据库

  20. 20

    ListView在android中使用数据库

  21. 21

    在Realm中使用预填充的数据库

  22. 22

    在 Rails 中使用数据库中的 JSON 填充表

  23. 23

    使用android在SQLite数据库表中使用WHERE子句检索值

  24. 24

    如何在Android应用程序中使用外部sqlite数据库

  25. 25

    如何在Android中使用有关sqlite数据库的insert()方法

  26. 26

    在Android中使用rawQuery和rowid从sqlite数据库中选择一行

  27. 27

    尝试从SQLite数据库填充ListView

  28. 28

    从数据库(SQLite)填充TextWatcher

  29. 29

    从SQLite数据库填充表布局

热门标签

归档