Search Unity

SQLiteKit

Discussion in 'Assets and Asset Store' started by Oksana-Iashchuk, Sep 11, 2012.

  1. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Hello rocki

    Sorry for late reply,

    Yes it possible, you will need represent you GameObject into byte[] and insert to database as BLOB, by using Bind(byte[])
     
  2. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Please email me, I will send an update, some how after upload reference have been broken,

    orangetree.unity@gmail.com
     
  3. EmeralLotus

    EmeralLotus

    Joined:
    Aug 10, 2012
    Posts:
    1,462
    Hello, I emailed you earlier today. Can you please send the demo file. Thanks.
     
  4. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Sure I did that, lets talk
     
  5. tal1m0n

    tal1m0n

    Joined:
    Jun 9, 2013
    Posts:
    5
    Apologies for these dumb questions. I've watched both your tutorials and have set my project up identical to yours. Here I have a table where
    I am trying to store the "Maximum/Minimum" health of each Player.

    The query, "SELECT curHealth FROM playerStats WHERE id = '1' is working when I run it on my SQLite database but when using in the scene I get the error "SQLite fail to bind integer with error: bind or column index out of range.


    I'm not sure why this is considered out of range?

    $playerStats.jpg $playerStatstable.jpg


    This is the full error:"Exception: SQLite fail to bind integer with error: bind or column index out of range
    SQLiteQuery.BindAt (Int32 integer, Int32 bindAt) (at Assets/sqlitekit/SQLiteQuery.cs:68)
    SQLiteQuery.Bind (Int32 integer) (at Assets/sqlitekit/SQLiteQuery.cs:59)
    HutongGames.PlayMaker.Actions.SQLiteExecute.QueryComplete (.SQLiteQuery qr, System.Object state) (at Assets/sqlitekit/Playmaker Integration/Scripts/SQLiteExecuteAction.cs:63)
    SQLiteAsync.CreateQueryComplete (System.Object state) (at Assets/sqlitekit/SQLiteAsync.cs:223)
    ThreadQueue+WorkingThread.Update () (at Assets/sqlitekit/ThreadQueue.cs:180)
    ThreadQueue.Update () (at Assets/sqlitekit/ThreadQueue.cs:242)

    "
     
  6. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Hello tal1m0n

    Please check the type of "id" field.
    From your request <SELECT curHealth FROM playerStats WHERE id = '1'> it's clean that is a string.
    If you will have id as Integer your request will be like that: <SELECT curHealth FROM playerStats WHERE id = 1>

    One more thing in your crash log there is bind but in your screen shot no bind action.
    Please email me your scene if possible

    Best regards,
     
    Last edited: Jul 10, 2013
  7. WJ_Fitzgerald

    WJ_Fitzgerald

    Joined:
    Jul 10, 2012
    Posts:
    1
    Can someone tell me if they know (or have successfully made this happen) if this addon can communicate with Microsoft SQL 2008 R2 database? I am looking for a solution for my 2D GUI to draw data from this database somehow, while maintaining the security that this database offers.

    Forgive my ignorance, I'm new to databases (but know that this is the database that must be used).

    Thank you for your time in clarifying this!
     
  8. b.sechter@gloops

    b.sechter@gloops

    Joined:
    Apr 24, 2013
    Posts:
    2
    What boilerplate code is used to copy the database from the bundle to persistent storage? What I have works on the PC, but it fails to copy the file on both iOS and Android. See lines 25 ~ 31 in the listing below.
    Code (csharp):
    1. public class DatabaseController : MonoBehaviour
    2. {
    3.     public bool   clearUserData          = false;
    4.     public string userDatabaseFilename   = "user.db"; // read write
    5.     public string systemDatabaseFilename = "system.db"; // read only
    6.     private SQLiteDB userDatabase;
    7.     private SQLiteDB systemDatabase;
    8.    
    9.     void Awake()
    10.     {
    11.         // initialize and open databases
    12.         userDatabase   = InitializeDatabase(filename:userDatabaseFilename,   force:clearUserData);
    13.         systemDatabase = InitializeDatabase(filename:systemDatabaseFilename, force:true);
    14.     }
    15.  
    16.     void OnDestroy()
    17.     {
    18.         // close databases
    19.         userDatabase.Close();
    20.         systemDatabase.Close();
    21.     }
    22.    
    23.     SQLiteDB InitializeDatabase(string filename, bool force=false)
    24.     {
    25.         string bundlePath = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
    26.         string livePath   = System.IO.Path.Combine(Application.persistentDataPath,  filename);
    27.         if (force || !System.IO.File.Exists(livePath))
    28.         {
    29.             System.IO.File.Copy(bundlePath, livePath, force);
    30.             Debug.Log(string.Format("Copied {0} from {1} to {2}.", filename, bundlePath, livePath));
    31.         }
    32.         SQLiteDB result = new SQLiteDB();
    33.         result.Open(livePath);
    34.         Debug.Log(string.Format("Opened Database : {0} ( {1} )", livePath, result));
    35.         return result;
    36.     }
    37. }
    The above gives the following logcat error on Android. The iOS version thows a EXC_BAD_ACCESS, probably for the same reason.
    Code (csharp):
    1. I/Unity   (22164): FileNotFoundException: jar:file:///mnt/asec/com.mycompany.myproject.dev-1/pkg.apk!/assets/user.db does not exist
    What should I do to solve this problem? Thank you.
     
  9. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Hello WJ_Fitzgerald

    Sorry no. it doen't support MS SQL.
     
  10. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Hello b.sechter@gloops

    Please check demos and specially DemoObject.cs - there is example how to copy database,
    you need use WWW to work on Android and "/Raw/" folder on IOS.

    Best regards

    email me directly if help is require
     
  11. b.sechter@gloops

    b.sechter@gloops

    Joined:
    Apr 24, 2013
    Posts:
    2
    Thank you much. I finally managed to get everything to work on iOS, Android and Mac OSX. Working code below, if anyone is interested.
    Code (csharp):
    1. /* CC0, do whatever you want with this code
    2. http://creativecommons.org/publicdomain/zero/1.0/legalcode
    3.  */
    4. using UnityEngine;
    5. using System.Collections;
    6. using System;
    7. using System.IO;
    8.  
    9. public class DatabaseController : MonoBehaviour
    10. {
    11.     public bool   clearUserData          = false;
    12.     public string userDatabaseFilename   = "user.db"; // read write
    13.     public string systemDatabaseFilename = "system.db"; // read only
    14.     private SQLiteDB userDatabase;
    15.     private SQLiteDB systemDatabase;
    16.    
    17.     private void Awake()
    18.     {
    19.         // initialize and open databases
    20.         userDatabase   = InitializeDatabase(filename:userDatabaseFilename,   force:clearUserData);
    21.         systemDatabase = InitializeDatabase(filename:systemDatabaseFilename, force:true);
    22.     }
    23.  
    24.     private void OnDestroy()
    25.     {
    26.         // close databases
    27.         userDatabase.Close();
    28.         systemDatabase.Close();
    29.     }
    30.    
    31.     private SQLiteDB InitializeDatabase(string filename, bool force=false)
    32.     {
    33.         string bundlePath = BundleDatabasePath(filename);
    34.         string livePath   = LiveDatabasePath(filename);
    35.         if (force || !System.IO.File.Exists(livePath))
    36.         {
    37.             byte[] data = DatabaseData(filename);
    38.             if (null != data)
    39.             {
    40.                 try
    41.                 {
    42.                     using (FileStream stream = new FileStream(livePath, FileMode.Create, FileAccess.Write))
    43.                     {
    44.                         stream.Write(data, 0, data.Length);
    45.                     }
    46.                     Debug.Log(string.Format("SQLite, copied database : {0} ({1} bytes)", livePath, data.Length));
    47.                 }
    48.                 catch (Exception exception)
    49.                 {
    50.                     Debug.Log(string.Format("SQLite, error copying database : {0}", exception.ToString()));
    51.                 }
    52.             }
    53.             else
    54.             {
    55.                 Debug.Log(string.Format("SQLite, empty database : {0}", livePath));
    56.             }
    57.         }
    58.         SQLiteDB result = new SQLiteDB();
    59.         try
    60.         {
    61.             result.Open(livePath);
    62.             Debug.Log(string.Format("SQLite, opened database : {0} ( {1} )", livePath, result));
    63.         }
    64.         catch (Exception exception)
    65.         {
    66.             Debug.Log(string.Format("SQLite, error opening database : {0}", exception.ToString()));
    67.         }
    68.         return result;
    69.     }
    70.    
    71.     public string BundleDatabasePath(string filename="")
    72.     {
    73.         string result;
    74.         #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
    75.             result = System.IO.Path.Combine(string.Format("file://{0}", Application.streamingAssetsPath), filename);
    76.         #elif UNITY_ANDROID
    77.             result = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
    78.         #elif UNITY_IPHONE
    79.             result = System.IO.Path.Combine(Application.dataPath, string.Format("Raw/{0}", filename));
    80.         #elif UNITY_WEBPLAYER
    81.             result = System.IO.Path.Combine("StreamingAssets/", filename)); // untested
    82.         #endif
    83.         return result;
    84.     }
    85.  
    86.     public string LiveDatabasePath(string filename="")
    87.     {
    88.         string result = System.IO.Path.Combine(Application.persistentDataPath,  filename);
    89.         return result;
    90.     }
    91.    
    92.     private byte[] DatabaseData(string filename)
    93.     {
    94.         byte[] result = null;
    95.         string path = BundleDatabasePath(filename);
    96.         #if UNITY_ANDROID || UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER
    97.             WWW www = new WWW(path);
    98.             while (!www.isDone) {} // blocking
    99.             result = www.bytes;
    100.         #elif UNITY_IPHONE
    101.             try
    102.             {  
    103.                 using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
    104.                 {
    105.                     result = new byte[stream.Length];
    106.                     stream.Read(result, 0, (int)stream.Length);
    107.                 }          
    108.             }
    109.             catch (Exception exception)
    110.             {
    111.                 Debug.Log(string.Format("SQLite, error reading database : {0}", exception.ToString()));
    112.             }
    113.         #endif
    114.         return result;
    115.     }
    116.    
    117.     private SQLiteQuery Query(SQLiteDB db, string query)
    118.     {
    119.         SQLiteQuery result = null;
    120.         try {
    121.             result = new SQLiteQuery(db, query);
    122.         }
    123.         catch (Exception exception)
    124.         {
    125.             Debug.Log(string.Format("SQLite, query error : {0}", exception.ToString()));
    126.         }
    127.         return result;
    128.     }
    129.    
    130.     public SQLiteQuery UserQuery(string query)
    131.     {
    132.         Debug.Log(string.Format("SQLite, user query : {0}", query));
    133.         return Query(userDatabase, query);
    134.     }
    135.    
    136.     public SQLiteQuery SystemQuery(string query)
    137.     {
    138.         Debug.Log(string.Format("SQLite, system query : {0}", query));
    139.         return Query(systemDatabase, query);
    140.     }
    141. }
     
  12. Mr.Reaper

    Mr.Reaper

    Joined:
    Oct 1, 2012
    Posts:
    10
    Hello,
    How would I go about receiving the return value in this case:

     
  13. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    from sqlite.org:

    PRAGMA table_info(table-name);

    This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.


    so please try qr.GetString("name") and qr.GetString("type"). buy be aware that sqlite has variable column types it is mean each row are different!!!!
    the best just take column names and types directly from qr.

    Best regards
     
  14. Mr.Reaper

    Mr.Reaper

    Joined:
    Oct 1, 2012
    Posts:
    10
    Hi Oksana. Thanks for your reply, got it working great now :D
     
    Last edited: Sep 13, 2013
  15. concave

    concave

    Joined:
    Aug 28, 2012
    Posts:
    49
    @sqlite kit - developer
    i have problems with sklite kit solution too - when i put it in streaming assets sometimes the db file is not streamed properly and seems to be corrupted
    (wrongfile size not openable by sqlite editor) - whats with this issue? how did you test your package? what is your solution?

    @b.sechter@gloops
    where do i have to put the db files in your solution? also in the streaming assets ?
     
    Last edited: Sep 25, 2013
  16. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Please do update from last version, Unity has bug if you using www.Done not from corantine function will return true even if file is not ready. I changed demo objects. You need to open database by WWW from StartCorantine function.

    WWW www = new WWW(path);

    while (!www.isDone) {} // blocking <--- Unity bug is here

    result = www.bytes;


    To run demo, yes. just copy database to streaming assets
     
  17. sinergy

    sinergy

    Joined:
    Apr 24, 2013
    Posts:
    5
    I would like to know if I would like to use the follow syntax supported by SQLite, what Field Name should I use to get the query result?

    Code (csharp):
    1. string statement = "SELECT date('now');";
    2. SQLiteQuery query = new SQLiteQuery(db, statement);
    3. query.Step();
    4. rowid = query.GetString("__Field Name Here ?__")
    5. query.Release();
    6.  
    Since SQLite do provide some really useful core functions so that I would like to know how could I use them, thanks
     
  18. Sea-Dragon

    Sea-Dragon

    Joined:
    May 24, 2013
    Posts:
    12
    Hello sinergy

    You could use follow

    Code (csharp):
    1. string statement = "SELECT date('now') AS mydate;";
    2. SQLiteQuery query = new SQLiteQuery(db, statement);
    3. query.Step();
    4. rowid = query.GetString("mydate");
    5. query.Release();
    6.  
    or you could get field names if you want to know how original http://sqlite.org will named your request without response field declaration
    Code (csharp):
    1.  
    2. qr.Names -> ["__Field Name Here ?__"]
    3.  
    Best regards
     
  19. sinergy

    sinergy

    Joined:
    Apr 24, 2013
    Posts:
    5
    wooh! awesome!
    Almost forget that we could use the alias method.
    Thank you @Sea Dragon for providing and reminding this tip!
     
  20. StickSports

    StickSports

    Joined:
    Feb 12, 2013
    Posts:
    3
    Does SQLiteKit work on windows phone?

    Thanks
     
  21. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    No, it's not ready, Windows phone has abnormal file system which require big changes in library. Because it use System.IO a lot which is absent on Windows phone. It will adopted in future.
     
  22. gshape

    gshape

    Joined:
    Aug 8, 2012
    Posts:
    104
    Hi Oksana! I have a "DATETIME" field, may I know how can I get it with SQLiteKit please?
    If possible, could you please show me the sample code?
    Thanks.
     
  23. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Hi gshape!

    I will extend qr.GetDateTime("date");
    But now you could use two solutions:
    1. DateTime.Parse(qr.GetString("date"));

    2. store data in FLOAT field by converting

    float date = System.DateTime.UtcNow.ToOADate();
    put in your table,
    read by:
    System.DateTime.FromOADate(date);
     
  24. gshape

    gshape

    Joined:
    Aug 8, 2012
    Posts:
    104
    Thank you!
     
  25. flamy

    flamy

    Joined:
    Feb 7, 2011
    Posts:
    194
    Hello there,

    I am using sqlite kit for one of my projects, Writing to sqlite is very fast but Reading from Sqlite Kit is very slow. it takes like 50 seconds to read 1800 data rows from a 16 column table. Is this is the normal performance or Am I missing something?



    Edit: Never mind my noobness, the problem was with database structuring. SqliteKit works like charm
     
    Last edited: Jan 27, 2014
  26. Deleted User

    Deleted User

    Guest

    Hello there,
    just started using SQLite Kit.
    But I have a question. I need to load all data from a table in a list. In standard using I do something like this:


    function Start ()
    {

    // Gather a list of records from the database

    records = new List.<ManufacturerRims>();
    records = dbManager.Query.<ManufacturerRims>
    (
    "SELECT " +
    "idManufacturer, " +
    "ManufacturerName " +

    "FROM " +
    "ManufacturerRims " +
    "ORDER BY " +
    "ManufacturerName "
    );

    }

    function OnGui ()
    {

    for (var m : int = 0; m < records.Count; m++)
    {
    buttonIdManufacturerRims=(records[m].idManufacturer);
    ManufacturerRimName = records[m].ManufacturerName;
    }
    }

    But 'List' is only working with 'using system.data' (which is not possible without Pro License, the reason why I use this asset). How is the equivalent in this asset? How can I set up this list for further using.
    I am giving this value to a function in DAIKON FORGE, where I set upp a dynamic button list, using the entries of this table as names.
    would be nice if someone has a solution.
    sunny regards
     
    Last edited by a moderator: Mar 22, 2014
  27. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Yep, just do next:

    List<string> strs = new List<string>()
    SQLiteQuery qr = new SQLiteQuery(db, "SELECT ....");
    while(qr.Step())
    {
    strs.Add(qr.GetString("your field name here"));
    }
    qr.Release();


    I hope it helps
     
  28. Deleted User

    Deleted User

    Guest

    Hi,

    yes it helps a little. And I am sorry asking more (but I am newbie and still learningthis all)
    I have set up a counter who builds the quantity of buttons now, but I can't see how to bring the button text (which is the content of fieldname (in my case ManufacturerRim) to the buttons. Because strs or ManufacturerRim only holds the last read entry/row of th table.
    You can see the result at the attached image. it counts the rows of the table, create the buttons and holds the last content of ManufacturerRim as button text. So, the question still is, how bring I each content to the buttons?
    I mean there must be something like ManufacturerRim(count) or whatever.


    This is my code for reading table and creating buttons with the value of variable 'counter'


    // read the table

    while(qr.Step())
    {
    strs.Add (qr.GetString("ManufacturerName"));
    ManfacturerRim = qr.GetString("ManufacturerName");
    ManfacturerRim .ToString();

    for(int c=0; c<strs.Count; c++)
    {
    counter = c;

    }
    //UnityEngine.Debug.Log (" Name: " + ManfacturerRim);

    }


    And I have a second question: When I start in gameplay of unity I can see this working. If I build this to my android device, I cant see buttons.I think this comes because of no having the database in the app. Could it be that there is no database in the build? how do I set up this?

    Would be glad if you can help me once more.

    $buttonlist.png
     
    Last edited by a moderator: Mar 23, 2014
  29. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    there is copy require on android, please copy database from StreamingAsset to persistent folder as in example, because on android StreamingAssets is a ZIP storage.

    Best regards
     
  30. Deleted User

    Deleted User

    Guest

    Hi Oksana,
    thanks for the hint.
    this seems to work, but if I make the build to the smartphone I recognize that the database on that mobile device has 0 bytes. Do you know how it comes?
    If I copy the database to that device again manually the application is working and show the buttons as expected.
    And do you have an idea for the first question in the last task?
     
    Last edited by a moderator: Mar 24, 2014
  31. Deleted User

    Deleted User

    Guest

    ok, in the meantime I solved one of my questions.
    But I still have the problem, while building the app and transfer it to th phone, that the database is empty.
    As I tolld, if I am copying it to the phonee after intallation the apk, it works perfectly.
    So, first it is time to say thank you very much for your great job.
     
  32. darkmax

    darkmax

    Joined:
    Feb 21, 2012
    Posts:
    83
    Hi I have a question?
    When I have to do several inserts on the DB, how can i bind the data to my query?
    I'm doing this, but without success
    Code (csharp):
    1.  
    2. qr = new SQLiteQuery(db, "INSERT OR REPLACE INTO User VALUES(?,?,?,?)"); //idUser, name, lastname, age
    3. foreach(Insert i in list_inserts)
    4. {
    5.     qr.Bind(i.idUser);
    6.     qr.Bind(i.name);
    7.     qr.Bind(i.lastname);
    8.     qr.Bind(i.age);
    9.     qr.Step();
    10. }
    11. qr.Release();
    12.  
    So how I can re-use the query and just change the variables?
     
    Last edited: Apr 8, 2014
  33. hiroki802

    hiroki802

    Joined:
    Feb 16, 2014
    Posts:
    12
    Hi,

    I bought SQLiteKit and I'm testing it.

    I made a sqlite3 database which has English and Japanese words like a dictionary.
    I put the database file in the StreaminAssets folder.

    I'd like to access to the meaning of the word like "select japanese from tango where english='math' "
    I can execute the query on sqlite app on my Macbook.
    $????????? 2014-03-31 16.44.37.JPG

    I'm trying to connect to the database through SQLiteKit, but I cannot do it.
    $????????? 2014-03-31 16.33.08.JPG

    It would be happy if you gave me an advice.

    - Hiroki




    *************************************************************************

    using UnityEngine;
    using System.Collections;

    public class SQLitetest : MonoBehaviour {

    void Start () {

    //create a new database
    SQLiteDB db = new SQLiteDB();

    //connect to the detabase
    db.Open(Application.streamingAssetsPath + "/test.db");

    //make a query
    SQLiteQuery qr = new SQLiteQuery(db, "SELECT * from tango where english='good'");

    //get a result and put the value to a variable
    string result = qr.GetString("japanese");

    //print the string on the console window
    print(result);

    db.Close();
    }

    }
     
    Last edited: Mar 31, 2014
  34. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Hi, every Bind increment binding argument index silently.
    You need to use BindAt(1,...); BindAt(2,...)....then it be ok.
     
  35. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126

    Please be aware that streaming assets is read only on device, so you will not able modify database, so you need copy to persistence folder. please look at examples, it has good example how to do that.
     
  36. rahuxx

    rahuxx

    Joined:
    May 8, 2009
    Posts:
    537
    How can I use local CSV file to create database?
    I have it in my assests folder.
    How to use it?

    Also any chance of integrating it with uScript?
     
    Last edited: Apr 5, 2014
  37. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126

    local CSV file you could modify editor import script for google docs, just a little cz CSV come from google as well.

    uScript, you mean UnrealScript?
     
  38. Vern_Shurtz

    Vern_Shurtz

    Joined:
    Mar 6, 2009
    Posts:
    264
    I believe he is referring to one of the other]visual scripting assets for Unity.

    http://www.detoxstudios.com/
     
  39. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    ups, ok I will check what it is.

    Thanks
     
  40. Vern_Shurtz

    Vern_Shurtz

    Joined:
    Mar 6, 2009
    Posts:
    264
    Hi there,

    I wanted to thank you again for the assistance you gave me last week. I've been able to implement just about everything I need to do. The one area that is still giving me issues is transferring the SQLite db to a web server. I have a localhost set up using a PHP Dev Server setup from www.easyphp.org and have tried with a number of PHP scripts to receive the file but without any luck. I am not a PHP programmer so I am pretty much dropping in code snippets and hoping for the best. :/

    Would it be alright if I posted the custom playMaker action code you wrote for uploading from the persistent folder here for others to use and to help set up a good system to transfer a db to a web server using SQLiteKit's playMaker integration? This, I would think will benefit the community.

    Here is a page that I have been going over and trying to see how it fits with the action you wrote for me.

    Thanks again.

    Vern
     
    Last edited: Apr 19, 2014
  41. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    Sure, and after I will add it in next update too. Thanks !
     
  42. Vern_Shurtz

    Vern_Shurtz

    Joined:
    Mar 6, 2009
    Posts:
    264
    Here is the playMaker Action code to Upload SQLiteKit. What I am trying to figure out is the PHP code on the web server to receive the file.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System;
    4. using System.IO;
    5. using System.Collections;
    6.  
    7. namespace HutongGames.PlayMaker.Actions
    8. {
    9.     [ActionCategory("SQLiteKit")]
    10.     [Tooltip("Upload SQLite database.")]
    11.     public class UploadFromPersistent : FsmStateAction
    12.     {
    13.         [RequiredField]
    14.         [UIHint(UIHint.FsmString)]
    15.         [Tooltip("Url")]
    16.         public FsmString url;
    17.        
    18.         [RequiredField]
    19.         [UIHint(UIHint.FsmString)]
    20.         [Tooltip("Copied database file full path")]
    21.         public FsmString persistentFilename;   
    22.        
    23.         [Tooltip("On succeeded file copy.")]
    24.         public FsmEvent onSuccess;
    25.        
    26.         [Tooltip("On file copy fail.")]
    27.         public FsmEvent onFail;
    28.        
    29.         WWW www;
    30.         string filename;
    31.        
    32.         public override void Reset()
    33.         {
    34.             onSuccess = null;
    35.             onFail = null;
    36.         }
    37.        
    38.         public override void OnUpdate ()
    39.         {
    40.             base.OnUpdate ();
    41.            
    42.             if(www != null)
    43.             {
    44.                 if(www.isDone)
    45.                 {
    46.                     if(www.error != null)
    47.                     {
    48.                         Fsm.Event(onFail);
    49.                     }
    50.                     else
    51.                     {
    52.                         Fsm.Event(onSuccess);
    53.                     }
    54.                     www = null;
    55.                 }
    56.             }  
    57.  
    58.        
    59.         }
    60.  
    61.         public override void OnEnter()
    62.         {
    63.            
    64.             // persistant database path.
    65.             filename = Application.persistentDataPath + "/" + persistentFilename;
    66.  
    67.            
    68.             // check if database already exists.
    69.             if(File.Exists(filename))
    70.             {  
    71.                 www = new WWW(url.Value,File.ReadAllBytes(filename));
    72.             }
    73.             else
    74.             {
    75.                 Fsm.Event(onFail);
    76.                 Finish();
    77.             }
    78.         }
    79.        
    80.     }
    81. }
    82.  
    It would also be helpful to have the ability to get a response from the server that the file has been received.

    Thanks
     
    Last edited: Apr 19, 2014
  43. Vern_Shurtz

    Vern_Shurtz

    Joined:
    Mar 6, 2009
    Posts:
    264
    Well I am able to transfer a file to a local host using code from this Unity Answers page.

    I have tried to figure out how to edit the playMaker Action code above but so far no luck. The PHP script appears to be what I need. I just need a little help connecting the two. Here is the PHP script;

    Code (csharp):
    1.  
    2. <?php
    3.    if(isset($_FILES['theFile']))
    4.    {
    5.       print("Success! ");
    6.       print("tmpName: " . $_FILES['theFile']['tmp_name'] . " ");
    7.       print("size: " . $_FILES['theFile']['size'] . " ");
    8.       print("mime: " . $_FILES['theFile']['type'] . " ");
    9.       print("name: " . $_FILES['theFile']['name'] . " ");
    10.  
    11.       move_uploaded_file($_FILES['theFile']['tmp_name'], "uploads/" . $_FILES['theFile']['name']);
    12.    } else
    13.    {
    14.       print("Failed!");
    15.    }
    16. ?>
    17.  
    Any help would be appreciated.

    Vern
     
    Last edited: Apr 20, 2014
  44. darkmax

    darkmax

    Joined:
    Feb 21, 2012
    Posts:
    83
    Hi me again, I been trying to resolve my issue about inserting several rows, with a similar code like this one:
    Code (csharp):
    1.  
    2. public class Insert {
    3.   public int idUser {get; set;}
    4.   public string name {get;set;}
    5.   public string lastname {get;set;}
    6.   public int age {get;set;}
    7. }
    8. .
    9. .
    10. .
    11. db.open(filename);
    12. qr = new SQLiteQuery(db, "INSERT OR REPLACE INTO User VALUES(?,?,?,?)"); //idUser, name, lastname, age
    13.  
    14. foreach(Insert i in list_inserts)
    15.  
    16. {
    17.  
    18.     qr.BindAt(i.idUser, 1);
    19.  
    20.     qr.BindAt(i.name, 2);
    21.  
    22.     qr.BindAt(i.lastname, 3);
    23.  
    24.     qr.BindAt(i.age, 4);
    25.  
    26.     qr.Step();
    27.  
    28. }
    29.  
    30. qr.Release();
    31.  
    But doesn't work, throws this error:

    System.Exception: SQLite fail to bind integer with error: library routine called out of sequence
    at SQLiteQuery.BindAt (Int32 integer, Int32 bindAt) [0x0002c]

    Any idea of why this is happening?


    UPDATE 1:

    this works but I'm creating a query every time I want to insert something, instead of re-using the query of before and just binding the new data.
    Code (csharp):
    1.  
    2. db.open(filename);
    3. foreach(Insert i in list_inserts)
    4.  
    5. {
    6.     qr = new SQLiteQuery(db, "INSERT OR REPLACE INTO User VALUES(?,?,?,?)"); //idUser, name, lastname, age
    7.     qr.BindAt(i.idUser, 1);
    8.  
    9.     qr.BindAt(i.name, 2);
    10.  
    11.     qr.BindAt(i.lastname, 3);
    12.  
    13.     qr.BindAt(i.age, 4);
    14.  
    15.     qr.Step();
    16.  
    17.    qr.Release();
    18.  
    19. }
    20.  
    So anyone any clues of how re-using the query for several inserts?
     
    Last edited: Apr 22, 2014
  45. rahuxx

    rahuxx

    Joined:
    May 8, 2009
    Posts:
    537
    No uScript from DetoxStudio- http://www.detoxstudios.com/
    really need this.
     
  46. Vern_Shurtz

    Vern_Shurtz

    Joined:
    Mar 6, 2009
    Posts:
    264
    Well I have this working as a normal script attached to an empty game object and using "Send Message" Action in playMaker to initiate the process and assign the name of the file which it is getting from the persistent folder. Here is the code;

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class SendFile : MonoBehaviour {
    6.  
    7.     //public string m_LocalFileName = "Testdb.db";
    8.     public string m_URL = "http://localhost/test/upload_file.php";
    9.  
    10.     string filename;
    11.  
    12.     void UploadStart(string name)
    13.     {
    14.         filename = Application.persistentDataPath + "/" + name;
    15.         Debug.Log(filename);
    16.        
    17.         UploadFile(filename,m_URL);
    18.     }
    19.  
    20.  
    21.     void UploadFile(string localFileName, string uploadURL)
    22.     {
    23.         StartCoroutine(UploadFileCo(localFileName, uploadURL));
    24.     }
    25.    
    26.     IEnumerator UploadFileCo(string localFileName, string uploadURL)
    27.     {
    28.  
    29.         WWW localFile = new WWW("file:///" + localFileName);
    30.         yield return localFile;
    31.         if (localFile.error == null)
    32.             Debug.Log("Loaded file successfully");
    33.         else
    34.         {
    35.             Debug.Log("Open file error: "+localFile.error);
    36.             yield break; // stop the coroutine here
    37.         }
    38.        
    39.         WWWForm postForm = new WWWForm();
    40.         // version 1
    41.         //postForm.AddBinaryData("theFile",localFile.bytes);
    42.        
    43.         // version 2
    44.         postForm.AddBinaryData("theFile",localFile.bytes,localFileName,"text/plain");
    45.        
    46.         WWW upload = new WWW(uploadURL,postForm);        
    47.         yield return upload;
    48.         if (upload.error == null)
    49.             Debug.Log("upload done :" + upload.text);
    50.         else
    51.             Debug.Log("Error during upload: " + upload.error);
    52.     }
    53. }
    54.  
    The PHP code from my previous post is relatively unchanged.

    So this will push a database stored in the persistent folder by SQLiteKit to a web server. I am half way there. Now I need to pull a database from the web server and put it into the persistent folder so I can use it with SQLiteKit. Here is where I am at thus far which isn't working as of yet.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class ReceiveFile : MonoBehaviour {
    6.  
    7.     public string url = "http://localhost/test/download_file.php?";
    8.  
    9.     void DownloadStart(string name)
    10.     {
    11.  
    12.         WWW www = new WWW(url + name);
    13.  
    14.         StartCoroutine(WaitForRequest(www));
    15.     }
    16.    
    17.     IEnumerator WaitForRequest(WWW www)
    18.     {
    19.         yield return www;
    20.        
    21.         // check for errors
    22.         if (www.error == null)
    23.         {
    24.             Debug.Log("WWW Ok!: " + www.data);
    25.         } else {
    26.             Debug.Log("WWW Error: "+ www.error);
    27.         }    
    28.     }
    29. }
    30.  
    and I am not sure where to start on the PHP end.

    So now I have two things to accomplish. First, GET a file from the web server and store it in either the persistent folder or the streaming asset folder. I would prefer the former. Second, is to get these scripts as Actions to be used in playMaker. I think this would be very beneficial to the community.

    Any assistance would be greatly appreciated.

    ~V~
     
    Last edited: Apr 22, 2014
  47. Vern_Shurtz

    Vern_Shurtz

    Joined:
    Mar 6, 2009
    Posts:
    264
    Ok, I have downloading figured out. This code is initiated using "Send Message" like the upload script. This required no PHP coding.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.IO;
    5.  
    6. public class ReceiveFile : MonoBehaviour {
    7.  
    8.     string url = "http://localhost/test/"; 
    9.  
    10.     string dbName = "";
    11.  
    12.     void startDownload(string filename)
    13.     {
    14.         dbName = filename;
    15.         Debug.Log(dbName);
    16.  
    17.         WWW www = new WWW(url + filename);
    18.         //WWW www = new WWW(url);
    19.  
    20.         StartCoroutine(DownloadFile(www));
    21.     }
    22.    
    23.     IEnumerator DownloadFile(WWW www)
    24.     {
    25.         yield return www;
    26.        
    27.         // check for errors
    28.         if (www.error == null)
    29.         {
    30.             Debug.Log("WWW Ok!: " + www.data);
    31.         } else {
    32.             Debug.Log("WWW Error: "+ www.error);
    33.         }
    34.         if (www.isDone)
    35.         {
    36.             File.WriteAllBytes(Application.persistentDataPath + "/" + dbName, www.bytes);              
    37.         }
    38.     }
    39. }
    40.  
    Again, it would be nice to see this as custom Actions. :)
     
  48. sudo23

    sudo23

    Joined:
    Dec 21, 2012
    Posts:
    4
    how im selecet row from id. or how im sum all colomn?
     
  49. EmeralLotus

    EmeralLotus

    Joined:
    Aug 10, 2012
    Posts:
    1,462
    Is there a chance to update this package with some of the features that were discussed in the forum. The current version is 1.9.3 (August 09, 2013), this is about 6 months ago.

    Cheers.
     
  50. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    I will do it in one week, I want to add WP8 support as well.