Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unity 3D + Android + SQLite Examples

Discussion in 'Android' started by fruki, Dec 7, 2011.

  1. fruki

    fruki

    Joined:
    Nov 30, 2011
    Posts:
    4
    Hi everybody I just learned some things in the past week about SQLite in Unity3D with Android and I thought I share them as I had to figure out most of it myself. All code in C#.

    Set up a database in the android device on runtime

    This is pretty easy, if you create a connection to a file that doesn't exist, it will be created. This is perfect to save data created by your application like scores or savegames. Note that once you created the database, it will stay there until deleted explicilty, so if you created it the first time, you will have to create a table before inserting values.

    Code (csharp):
    1. private IDbConnection dbcon;
    2. ...
    3.  
    4. public void OpenDB(string p)
    5.  
    6. {
    7.  
    8.     connection = "URI=file:" + Application.persistentDataPath + "/" + p; // we set the connection to our database
    9.  
    10.     //connection = "URI=file:" + p; // like this will NOT work on android
    11.  
    12.     Debug.Log(connection);
    13.  
    14.     dbcon = new SqliteConnection(connection);
    15.  
    16.     dbcon.Open();
    17.  
    18. }
    After this you can populate the database in different ways, I have attached a unitypackage to this post under the name "SQLite" where you can see an example. (note: there are many parts of the code which I took from internet examples)

    Load an already populated database in the android device

    This is trickier, as Android packs everything into a single file and sends it to the device. This means that if you want to send a file with it, you have to pack it in there and then somehow retrieve the data from the package. This comes in handy when you need a database already filled up with data, like a dictionary or NPC phrases.

    The way to do it is to create a folder named "StreamingAssets" in your assets folder. Then place your database inside, and at runtime "stream it" in realtime:

    Code (csharp):
    1. // check if file exists in Application.persistentDataPath
    2.  
    3. string filepath = Application.persistentDataPath + "/" + p;
    4.  
    5. if(!File.Exists(filepath))
    6.  
    7. {
    8.  
    9.     // if it doesn't ->
    10.  
    11.     // open StreamingAssets directory and load the db ->
    12.  
    13.     WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + p);  // this is the path to your StreamingAssets in android
    14.  
    15.     while(!loadDB.isDone) {}  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
    16.  
    17.     // then save to Application.persistentDataPath
    18.  
    19.     File.WriteAllBytes(filepath, loadDB.bytes);
    20.  
    21. }
    22.  
    23.        
    24.  
    25. //open db connection
    26.  
    27. connection = "URI=file:" + filepath;
    28.  
    29. dbcon = new SqliteConnection(connection);
    30.  
    31. dbcon.Open();
    You have the full code for this example in "SQLiteLoad"

    Hope it helps someone. :)

    P.S. Some users from this forum helped a lot, you can take a look at this conversation for more information: http://forum.unity3d.com/threads/97043-Sqlite-for-Android-help-please
     

    Attached Files:

    Last edited: Dec 7, 2011
  2. mpavlinsky

    mpavlinsky

    Joined:
    Oct 20, 2011
    Posts:
    8
    Thanks very much, this post was very helpful to me. I'm not loading a SQLLite database but the tip off about using the JARURL for accessing StreamingAssets is exactly what I needed for my AssetBundles.

    Thanks again.
     
  3. MonoSapiens

    MonoSapiens

    Joined:
    Apr 12, 2012
    Posts:
    79
  4. Meltdown

    Meltdown

    Joined:
    Oct 13, 2010
    Posts:
    5,816
    Hi Fruki,

    Thanks for the very helpful post!
    I've followed everything to a tee, but I'm getting the following error...

    System.EntryPointNotFoundException: sqlite3_column_origin_name

    Your SQLLiteLoad Package works fine on the Android device.
    Yet my own database doesn't. Any idea what could be causing this issue?
     
  5. Fayer

    Fayer

    Joined:
    Sep 7, 2012
    Posts:
    8
    I manage to do the connection and everything but I want to acces the DB from my computer, is there a way to do that?
     
  6. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    please, check this -> http://u3d.as/content/orange-tree/sqlite-kit/3ka
    That is 100% managed code, full SQLite3 support, all platforms.
    No native dependencies.
    There is example scene with test/demo code for platforms: WebPlayer, PC, Mac, Android, IPhone
     
  7. ina

    ina

    Joined:
    Nov 15, 2010
    Posts:
    1,080
    How does this compare to MonoSapiens? MonoSQLite
     
  8. Oksana-Iashchuk

    Oksana-Iashchuk

    Joined:
    Sep 10, 2012
    Posts:
    126
    If you like I could sent an example code to you. You will find how easy work with database by http://u3d.as/content/orange-tree/sqlite-kit/3ka . You will compare by your self. Portability was tested by Unity team on approval stage.


    // database file name.
    //
    string filename = Application.persistentDataPath + "/demo.db";

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

    // initialize database
    //
    db.Open(filename);

    // make a query object
    //
    SQLiteQuery qr = new SQLiteQuery(db, "SELECT * FROM test_values;");

    // read result
    //
    while( qr.Step() )
    {
    string astring = qr.GetString("str_field");
    byte[] ablob = qr.GetBlob("blob_field");
    }

    // release query object
    //
    qr.Release();

    // close database
    //
    db.Close();
     
    Last edited: Sep 11, 2012
  9. liliyanlyn

    liliyanlyn

    Joined:
    Jan 20, 2013
    Posts:
    1
    hello, i'm a newbie developing unity 3d app for android platform, I want to ask is it possible to making connection to "Streaming Assets" using javascript instead c# ?
    I can compile it well on my unity editor, but when I apply it on my android the application isnt work because cant get how to acess "Streaming Assets" for load the database.
     
  10. Compguru910

    Compguru910

    Joined:
    Mar 27, 2013
    Posts:
    4
    I dont know exactly how Unity interfaces with Android when it comes to databases. So, here is my experience working with preloaded databases. First, you want to make sure that your android database has a table called android_metadata in it with a field called locale. The value of that is of course, the locale that your working with. For english it is en_US. Secondly, for devices prior to 2.3, you cannot side load a database or any other asset that is larger than 1Mb, so keep that in mind when creating your database. The fix for this is splitting the file, then reassembling it on run. Here is how it works for a non Unity android app

    Create the database by attempting to open. If one doesnt exit, it is created.

    If the database is empty, open a stream writer and copy the existing database to the app data directory, overwritting the empty DB that android created. Use a for loop if the database has been split due to size issues.

    If anyone wants to see the Android code on how to do this, please let me know and I'll send you an example.
     
    sylun_fresh likes this.
  11. tredpro

    tredpro

    Joined:
    Nov 18, 2013
    Posts:
    515
    Im sorry but what area to you past the url to your database?
     
  12. hollym16

    hollym16

    Joined:
    Feb 21, 2013
    Posts:
    13
    I'm wanting to use a database to call different models at certain times on an Android app. Will this method make the app over 50mb if you're calling it from Streaming Assets folder?
     
  13. joao_pm

    joao_pm

    Joined:
    Apr 15, 2014
    Posts:
    1
    Thanks!
    This post was really useful for me, almost 3 years after it was written!
     
  14. kannan_unity3d

    kannan_unity3d

    Joined:
    Oct 30, 2013
    Posts:
    7
    i am currently working on tis.thanks guys
     
  15. Hippiecode

    Hippiecode

    Joined:
    Feb 13, 2012
    Posts:
    110
    hi to all..
    i used $SQLite.unitypackage for connect my database in android,its works well.Now I want to display the name of value where word="primary".Help me to get result.My db table is lik dis..And my code is this way

    kp word value
    1 bio poa
    2 primary pob
    3 primary pos

    Code (CSharp):
    1. string[,] result2 = SingleSelectWhere("petdef", "value", "word", "=", "'primary'");
    2.      
    3.         // Concatenate all the elements into a StringBuilder.
    4.         builderdisplay = new StringBuilder();
    5.         for (int i = 0; i < result2.GetLength(0); i++)
    6.         {
    7.             for (int j = 0; j < result2.GetLength(1); j++)
    8.             {
    9.                 builderdisplay[2].Append(result2[i,j]);
    10.                 builderdisplay[2].Append(' ');
    11.             }
    12.             subjectnamed.text = builderdisplay.ToString ();
    13.         }
     
  16. Hippiecode

    Hippiecode

    Joined:
    Feb 13, 2012
    Posts:
    110
    how to add and access one more field in $SQLite.unitypackage.Any idea about that.
     
  17. Simball

    Simball

    Joined:
    Sep 22, 2014
    Posts:
    2
    Hi,Meltdown,I met the same problem.It happened when I try to use "SqliteDataAdapter" to fill "dataset" . Can you tell me how you resolved it?
     
  18. Meltdown

    Meltdown

    Joined:
    Oct 13, 2010
    Posts:
    5,816
    Sorry I can't remember, I didn't use SQLlite in the end. But I would suggest finding the correct library. Mono.Data.SqlLite.dll.

    There are also some SQLite packages on the asset store that support Android, I would suggest buying one of these instead to save you a headache.

    Alternately look at an online hosted solution for your player data, which might be easier, as you can use it for all platforms.
     
  19. thready

    thready

    Joined:
    Sep 23, 2014
    Posts:
    7
    Hi everyone, I'm trying to use the package that fruki provided, and I have only the free version of Unity. I'm getting the errors that I have in the attached image... is it because I need to go pro or are these suggestions likely to work on the free version of unity?

    Thanks!
     

    Attached Files:

  20. monching21

    monching21

    Joined:
    Sep 27, 2014
    Posts:
    1
    me also, it looks like unity free version does not support the sqlliteclient T_T or im wrong T_T pls help us
     
  21. submiting

    submiting

    Joined:
    Oct 17, 2014
    Posts:
    1
    Hi fruki.
    Could you please compile libsqlite.so for Intel cpu also? We have found that current version cannot work with tablets that have Intel processor (System.DllNotFoundException: libSQLite3.so exception raises). Galaxy Tab 3 for example.

    Or maybe you can share source code?))
     
  22. adam_mehman

    adam_mehman

    Joined:
    Dec 11, 2014
    Posts:
    104
    Hi everybody i have one problem, my database simply wont create on my Samsung Galaxy S3 but it creates on PC.

    So it would be nice if someone can help me a bit...

    this is my code:

    Code (CSharp):
    1. void Start()
    2.     {
    3.         connectionString = "URI=file:" + Application.persistentDataPath + "/" + "gameDB";
    4.         OpenDatabase(connectionString);
    5.     }

    Code (CSharp):
    1. void OpenDatabase(string dbFilePath)
    2.     {
    3.         try
    4.         {
    5.             dbConnection = new SqliteConnection(dbFilePath);
    6.             if(dbConnection != null) {
    7.                 dbConnection.Open();
    8.  
    9.                 using (dbCommand = new SqliteCommand(dbConnection))
    10.                 {
    11.                     dbCommand.CommandText = "CREATE TABLE IF NOT EXISTS PlayedGames (Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, Score INTEGER NOT NULL DEFAULT 0)";
    12.                     dbCommand.Prepare();
    13.  
    14.                     dbCommand.ExecuteNonQuery();
    15.                 }
    16.             }
    17.         } catch (SqliteException ex) {
    18.             WriteToFile(ex.StackTrace);
    19.         } catch (System.Exception ex) {
    20.             WriteToFile(ex.Message);
    21.         } finally {
    22.             if(reader != null) {            
    23.                 reader.Close();
    24.                 reader = null;
    25.             }
    26.          
    27.             if(dbCommand != null) {
    28.                 dbCommand.Dispose();
    29.                 dbCommand = null;
    30.             }
    31.          
    32.             if(dbConnection != null) {            
    33.                 dbConnection.Close();
    34.                 dbConnection = null;
    35.             }
    36.         }
    37.     }
    After this code runs no database is created on Android and in catch block i get "sqlite3" message. What could that mean?

    Is it possible maybe because i put everything in folder /Plugins/ and not in /Assets/Plugins/ ?
     
    Last edited: Jan 16, 2015
  23. hexann

    hexann

    Joined:
    Nov 20, 2012
    Posts:
    1
    Hi ! Thanks so much, you are the real MVP !
     
  24. f4bo

    f4bo

    Joined:
    Oct 7, 2014
    Posts:
    21
    the Plugin folder must indeed be placed into Assets folder
    Anyhow, since this is an old thread and targetted for just Android, I suggest you to take also a peek at this all-purpose solution
     
  25. sawi

    sawi

    Joined:
    Feb 24, 2015
    Posts:
    11
    hello everyone
    i used the script of dbAcces proposed by fruki and this one.
    it works normally but the problem is that after building i din't work even when i click to the buttons nothing happen
    can someone help please
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System;
    4. using System.Collections;
    5. using System.Collections.Generic;
    6. using System.Data;
    7. using Mono.Data.SqliteClient;
    8.  
    9. public class usethedatabase : MonoBehaviour {
    10.    
    11.     public string  DatabaseName = "DBprodt.sqdb";
    12.    
    13.     // This is the name of the table we want to use
    14.     public string  TableName = "produittable";
    15.     private dbAccess db ;
    16.    
    17.     void Start ()
    18.     {
    19.         // Give ourselves a dbAccess object to work with, and open it
    20.         db = new dbAccess ();
    21.         db.OpenDB (DatabaseName);
    22.         // Let's make sure we've got a table to work with as well!
    23.         string tableName = TableName;
    24.         string[] columnNames = new string[]{"firstName", "lastName"};
    25.         string[] columnValues = new string[]{"text", "text"};
    26.         //try
    27.         //{
    28.         db.CreateTable (tableName, columnNames, columnValues);
    29.         //}
    30.        
    31.     }
    32.    
    33.     // These variables just hold info to display in our GUI
    34.     private string firstName = "First Name";
    35.     private string  lastName = "Last Name";
    36.     private int DatabaseEntryStringWidth = 100;
    37.     private Vector2 scrollPosition ;
    38.     private List<List<object>> databaseData = new List<List<object>> ();
    39.    
    40.     // This GUI provides us with a way to enter data into our database
    41.     //  as well as a way to view it
    42.     void OnGUI ()
    43.     {
    44.         GUI.Box (new Rect (25, 25, Screen.width - 50, Screen.height - 50), "");
    45.         GUILayout.BeginArea (new Rect (50, 50, Screen.width - 100, Screen.height - 100));
    46.         // This first block allows us to enter new entries into our table
    47.         GUILayout.BeginHorizontal ();
    48.         firstName = GUILayout.TextField (firstName, GUILayout.Width (DatabaseEntryStringWidth));
    49.         lastName = GUILayout.TextField (lastName, GUILayout.Width (DatabaseEntryStringWidth));
    50.         GUILayout.EndHorizontal ();
    51.        
    52.         if (GUILayout.Button ("Add to database"))
    53.         {
    54.             // Insert the data
    55.             InsertRow (firstName, lastName);
    56.             // And update the readout of the database
    57.             databaseData = ReadFullTable ();
    58.         }
    59.         // This second block gives us a button that will display/refresh the contents of our database
    60.         GUILayout.BeginHorizontal ();
    61.         if (GUILayout.Button ("Read Database"))
    62.         {
    63.             databaseData = ReadFullTable ();
    64.         }
    65.         if (GUILayout.Button ("Clear"))
    66.         {
    67.             databaseData.Clear ();
    68.         }
    69.         GUILayout.EndHorizontal ();
    70.        
    71.         GUILayout.Label ("Database Contents");
    72.         scrollPosition = GUILayout.BeginScrollView (scrollPosition, GUILayout.Height (100));
    73.         foreach (List<object> line in databaseData)
    74.         {
    75.             GUILayout.BeginHorizontal ();
    76.             foreach (object s in line)
    77.             {
    78.                 GUILayout.Label (s.ToString (), GUILayout.Width (DatabaseEntryStringWidth));
    79.             }
    80.             GUILayout.EndHorizontal ();
    81.         }
    82.        
    83.         GUILayout.EndScrollView ();
    84.         if (GUILayout.Button ("Delete All Data"))
    85.         {
    86.             DeleteTableContents ();
    87.             databaseData = ReadFullTable ();
    88.         }
    89.        
    90.         GUILayout.EndArea ();
    91.     }
    92.    
    93.     // Wrapper function for inserting our specific entries into our specific database and table for this file
    94.     private void InsertRow (string firstName, string lastName)
    95.     {
    96.         string[] values = new string[]{("'" + firstName + "'"), ("'" + lastName + "'")};
    97.         db.InsertInto (TableName, values);
    98.     }
    99.    
    100.     // Wrapper function, so we only mess with our table.
    101.     private List<List<object>> ReadFullTable ()
    102.     {
    103.         return db.ReadFullTable (TableName);
    104.     }
    105.    
    106.     // Another wrapper function...
    107.     private void DeleteTableContents ()
    108.     {
    109.         db.DeleteTableContents (TableName);
    110.     }
    111. }
    112.  
     
  26. kinichi

    kinichi

    Joined:
    Mar 29, 2015
    Posts:
    5
    Hey there :)
    Am a newbie developing unity 3d app for android platform and even for windows, am using unity v4.5 pro and I have chosen SQLite with SQLite browser to create my "local" database in unity 3D (in Csharp), just because SQLite is serverless (most important point),free,and does'nt require any configuration (just a matter of DLLs integration).
    Well, a part of my educational project is to find a way how to modify in my database and adding new values for example after building it ( when it is runnig maybe :confused: )..I still don't know how to do that but am keeping learning for the while and i 'll get my point if somebody helps me guys . I have two questions
    1- Is there any other suggestions for choosing other way to create my local database which must run later on android (serverless,free,matches with android platform)!? Or maybe any other addition that may works like SQLiteHelper For SQLite but i can iintegrate it with unity ofcourse..? I dont know ..any help please

    2- I found the example bellow of code project and I tried to build it on both windows and android..Well it works fine on unity editor but for build connexion is lost :(..i Tried but i coudn't resolve that problem
    Please any advices or help would be appreciated.(Here is the code) (5 classes)

    "Class CustomerEntity"

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4.  
    5. /// <summary>
    6. /// Entity class of Customer
    7. /// Mapped manually (!!!) from SampleDB
    8. /// </summary>
    9. public class CustomerEntity
    10. {
    11.     #region Fields
    12.    
    13.     private int iD;
    14.     private string userName;
    15.    
    16.     #endregion
    17.    
    18.     #region Properties
    19.     /// <summary>
    20.     /// Gets or sets the identifier.
    21.     /// </summary>
    22.     /// <value>
    23.     /// The identifier.
    24.     /// </value>
    25.     public int ID
    26.     {
    27.         get { return iD; }
    28.         set { iD = value; }
    29.     }
    30.     /// <summary>
    31.     /// Gets or sets the name of the user.
    32.     /// </summary>
    33.     /// <value>
    34.     /// The name of the user.
    35.     /// </value>
    36.     public string UserName
    37.     {
    38.         get { return userName; }
    39.         set { userName = value; }
    40.     }
    41.    
    42.     /// <summary>
    43.     /// Prevents a default instance of the <see cref="CustomerEntity"/> class from being created.
    44.     /// </summary>
    45.     private CustomerEntity()
    46.     {
    47.     }
    48.    
    49.     /// <summary>
    50.     /// Initializes a new instance of the <see cref="CustomerEntity"/> class.
    51.     /// </summary>
    52.     /// <param name="iD">The identifier</param>
    53.     /// <param name="userName">Name of the user.</param>
    54.     public CustomerEntity(int iD, string userName)
    55.     {
    56.         if (string.IsNullOrEmpty(userName))
    57.             throw new ArgumentNullException("userName cannot be null or empty !");
    58.        
    59.         this.iD = iD;
    60.         this.userName = userName;
    61.     }
    62.     #endregion
    63. }
    "Class CustomerEntityHelper"

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Data;
    5. using Mono.Data.Sqlite;
    6. using System;
    7.  
    8. /// <summary>
    9. /// CustomerEntityHelper Help you to retrieve the named Entity
    10. /// </summary>
    11. public class CustomerEntityHelper : DBHelper
    12. {
    13.     public List<CustomerEntity> GetAllCustomers()
    14.     {
    15.         List<CustomerEntity> result = new List<CustomerEntity>();
    16.         try
    17.         {
    18.             using (IDbConnection dbcon = new SqliteConnection(base.ConnString) as IDbConnection)
    19.             {
    20.                 dbcon.Open();
    21.                
    22.                 IDbCommand dbcmd = dbcon.CreateCommand();
    23.                 dbcmd.CommandText = "SELECT ID, UserName FROM Customer"; ;
    24.                
    25.                 using (IDataReader reader = dbcmd.ExecuteReader())
    26.                 {
    27.                     while (reader.Read())
    28.                     {
    29.                         int id = reader.GetInt32(0);
    30.                         string userName = reader.GetString(1);
    31.                        
    32.                         CustomerEntity customer = new CustomerEntity(id, userName);
    33.                         result.Add(customer);
    34.                     }
    35.                     reader.Close();
    36.                 }
    37.                 dbcon.Close();
    38.             }
    39.         }
    40.         catch (Exception ex)
    41.         {
    42.             Debug.LogError("GetAllCustomers thrown an error : " + ex.ToString());
    43.         }
    44.        
    45.         return result;
    46.     }
    47. }
    48.  
    "Class ConnectionResult "

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. /// <summary>
    5. /// ConnectionResult
    6. /// </summary>
    7. public class ConnectionResult
    8. {
    9.    
    10.     /// <summary>
    11.     /// ConnectionStatus
    12.     /// </summary>
    13.     public enum ConnectionStatus
    14.     {
    15.         Connected,
    16.         NotConnected
    17.     }
    18.    
    19.     private string connectionStringUsed;
    20.     private string errorMessage;
    21.     private ConnectionStatus status;
    22.    
    23.     public ConnectionStatus Status
    24.     {
    25.         get { return status; }
    26.         set { status = value; }
    27.     }
    28.     public string ConnectionStringUsed
    29.     {
    30.         get { return connectionStringUsed; }
    31.         set { connectionStringUsed = value; }
    32.     }
    33.     public string ErrorMessage
    34.     {
    35.         get { return errorMessage; }
    36.         set { errorMessage = value; }
    37.     }
    38. }
    39.  
    "Class DBHelper"

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Data;
    5. using Mono.Data.Sqlite;
    6. using System.IO;
    7.  
    8. /// <summary>
    9. /// DBHelper
    10. /// </summary>
    11. public class DBHelper
    12. {
    13.     #region Fields
    14.    
    15.     private string connString;
    16.     private string databaseCompletePath;//the path in your Unity Project and the DB Name
    17.    
    18.     #endregion
    19.    
    20.     #region Properties
    21.    
    22.     /// <summary>
    23.     /// Gets the connection string.
    24.     /// </summary>
    25.     /// <value>
    26.     /// The connection string.
    27.     /// </value>
    28.     public string ConnString
    29.     {
    30.         get { return connString; }
    31.     }
    32.    
    33.     #endregion
    34.    
    35.     #region Constructors
    36.    
    37.     /// <summary>
    38.     /// Initializes a new instance of the <see cref="DBHelper"/> class.
    39.     /// </summary>s
    40.     public DBHelper()
    41.     {
    42.         this.databaseCompletePath = "/SampleDB";
    43.         this.connString = string.Format("URI=file:{0}{1}", Application.dataPath,this. databaseCompletePath);
    44.        
    45.     }
    46.    
    47.     /// <summary>
    48.     /// Initializes a new instance of the <see cref="DBHelper"/> class.
    49.     /// </summary>
    50.     /// <param name="specificConnectionString">The specific connection string.</param>
    51.     /// <example>connection string could be: YourFloder1/Yourfolder2/YourDBName</example>
    52.     public DBHelper(string specificConnectionString)
    53.     {
    54.         this.databaseCompletePath = specificConnectionString;
    55.         this.connString = string.Format("URI=file:{0}/{1}",Application.dataPath,specificConnectionString);
    56.     }
    57.    
    58.     #endregion
    59.    
    60.     #region Methods
    61.    
    62.     /// <summary>
    63.     /// Checks the connection.
    64.     /// </summary>
    65.     /// <returns></returns>
    66.     public ConnectionResult CheckConnection()
    67.     {
    68.         ConnectionResult result = new ConnectionResult();
    69.         result.ConnectionStringUsed = this.connString;
    70.         try
    71.         {
    72.            
    73.             using (IDbConnection dbcon = new SqliteConnection(this.connString) as IDbConnection)
    74.             {
    75.                 //check if db file exist (with a bad name, sqlite try to create the DB and we don't want this behavior!)
    76.                 if (File.Exists(string.Format("{0}{1}", Application.dataPath,this.databaseCompletePath)))
    77.                 {
    78.                     dbcon.Open(); //Open connection to the database.
    79.                     result.Status = ConnectionResult.ConnectionStatus.Connected;
    80.                     dbcon.Close();
    81.                 }
    82.                 else
    83.                     throw new Exception("Database was not Found !");
    84.             }
    85.         }
    86.         catch (Exception ex)
    87.         {
    88.             result.ErrorMessage = ex.ToString();
    89.             result.Status = ConnectionResult.ConnectionStatus.NotConnected;
    90.         }
    91.        
    92.         return result;
    93.     }
    94.    
    95.     #endregion
    96.    
    97. }
    "Class SampleDB "

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Text;
    4. using System;
    5.  
    6. public class SampleDB : MonoBehaviour
    7. {
    8.    
    9.     private DBHelper dbHelper;
    10.     private bool isDBConnected;
    11.     private string checkResultMessage;
    12.     private string customerMessage;
    13.     /// <summary>
    14.     /// Starts this instance.
    15.     /// </summary>
    16.     void Start()
    17.     {
    18.         this.checkResultMessage = string.Empty;
    19.        
    20.         this.dbHelper = new DBHelper();//use the embedded DBHelper connection string.
    21.         this.isDBConnected = false; // before check, we consider the DB status as not connected.
    22.     }
    23.     void OnGUI()
    24.     {
    25.         int heightLocation = 100; //used for GUI
    26.         StringBuilder sbCustomer = new StringBuilder();// used to add string
    27.        
    28.         if (GUI.Button(new Rect(10, 10, 200, 30), "Check Connection"))
    29.         {
    30.             checkResultMessage = string.Empty;
    31.             ConnectionResult result = this.dbHelper.CheckConnection();
    32.             this.isDBConnected = (result.Status == ConnectionResult.ConnectionStatus.Connected);
    33.             checkResultMessage = (result.Status == ConnectionResult.ConnectionStatus.Connected) ?
    34.                 string.Format("Connection OK with connection string {0}", result.ConnectionStringUsed) : string.Format("Connection ERROR: {0}",result.ErrorMessage) ;
    35.         }
    36.         GUI.Label(new Rect(10, 50, 600, 60), checkResultMessage);
    37.        
    38.         if (this.isDBConnected)
    39.         {
    40.             if (GUI.Button(new Rect(220, 10, 200, 30), "Get customers"))
    41.             {
    42.                 CustomerEntityHelper customerHelper = new CustomerEntityHelper();
    43.                 foreach (CustomerEntity customer in customerHelper.GetAllCustomers())
    44.                 {
    45.                     sbCustomer.Append(string.Format("{0} - ID: {1}{2}", customer.UserName, customer.ID,Environment.NewLine));
    46.                     heightLocation += 40;
    47.                 }
    48.                 this.customerMessage = sbCustomer.ToString();
    49.             }
    50.         }
    51.        
    52.         GUI.Label(new Rect(10, 50, 600, 60), checkResultMessage);
    53.         GUI.Label(new Rect(10, 10 + heightLocation, 300, 600), this.customerMessage);
    54.        
    55.     }
    56. }
    BTW: I am new in the Forum and That's my first post,sorry for my bad english:p .Thank you even for reading this whole stuff :p
     
  27. moonglow

    moonglow

    Joined:
    Jun 20, 2013
    Posts:
    2
    I really appreciate your efforts.
     
  28. DeveshPandey

    DeveshPandey

    Joined:
    Sep 30, 2012
    Posts:
    221
    Hi,

    There is a plugin which is very easy to use without much knowledge about SQL, you should look at this plugin
    http://u3d.as/htX
     
  29. worlaz

    worlaz

    Joined:
    Oct 7, 2015
    Posts:
    9
    #Fruki.So basically the database is P. this works great for Pc but fails on Android any solution.
    Is www. the only solution to the loading assets at runtime.
     
  30. Hash-Buoy

    Hash-Buoy

    Joined:
    Jan 4, 2014
    Posts:
    33
    I ran into several problems , i kind off merged two solutions together and got it to work some how. My main problem was when i was trying to load an existing database form streaming assets on an android device with a split build (sounds daunting lol).

    What i realized was the file paths were screwed up and the database being copied was an empty database with no tables or information. I changed the OpenDB function in the dbAccess.cs class as per the following code. I have tested the following code on an android device with the split build and it all works fine.
    Hope this is useful :)

    This is the link to the project and this is the link for the class from where i copied the path logic.

    Code (CSharp):
    1.  
    2.     public void OpenDB(string DatabaseName)
    3.     {
    4.  
    5.             #if UNITY_EDITOR
    6.             var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
    7.             #else
    8.             // check if file exists in Application.persistentDataPath
    9.             var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);
    10.        
    11.             if (!File.Exists(filepath))
    12.             {
    13.                 Debug.Log("Database not in Persistent path");
    14.                 // if it doesn't ->
    15.                 // open StreamingAssets directory and load the db ->
    16.            
    17.                 #if UNITY_ANDROID
    18.                 var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
    19.                 while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
    20.                 // then save to Application.persistentDataPath
    21.                 File.WriteAllBytes(filepath, loadDb.bytes);
    22.                 #elif UNITY_IOS
    23.                 var loadDb = Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
    24.                 // then save to Application.persistentDataPath
    25.                 File.Copy(loadDb, filepath);
    26.                 #elif UNITY_WP8
    27.                 var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
    28.                 // then save to Application.persistentDataPath
    29.                 File.Copy(loadDb, filepath);
    30.            
    31.                 #elif UNITY_WINRT
    32.                 var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
    33.                 // then save to Application.persistentDataPath
    34.                 File.Copy(loadDb, filepath);
    35.                 #endif
    36.            
    37.                 Debug.Log("Database written");
    38.             }
    39.        
    40.             var dbPath = filepath;
    41.             #endif
    42.             //_connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
    43.             Debug.Log("Final PATH: " + dbPath);
    44.    
    45.         //open db connection
    46.         connection = "URI=file:" + dbPath;
    47.         Debug.Log("Stablishing connection to: " + connection);
    48.         dbcon = new SqliteConnection(connection);
    49.         dbcon.Open();
    50.     }
     
    mobgebuild likes this.
  31. cramz49

    cramz49

    Joined:
    Jan 7, 2016
    Posts:
    3
    Guys did you encounter this problem? "SqliteSyntaxException: no such table: petdef"
     
  32. irfan_omi22

    irfan_omi22

    Joined:
    Jan 9, 2016
    Posts:
    7
    Hi, Can anyone tell me, where the DataBase is Created in Android. Cuz, I problem I have is, When I update the database with some new info, in my PC it works fine, but in Android, even after deleting the app, old DataBase still exists. So somehow I need to write a code for replacing existing DataBase or delete the old one. Can anybody help me with the code or any method?
     
  33. zhulehao

    zhulehao

    Joined:
    Jul 4, 2015
    Posts:
    2
    the database exists in data/data/.... if you want to get files,you should first get root priority
     
  34. elduderinoU3

    elduderinoU3

    Joined:
    Jul 8, 2017
    Posts:
    2
    Hello,

    I have still the same problem. On Unity I can show all my entries from database in the game view, but if i build an apk and copy it to android (I must change settings from .Net2.0 subset to .Net2.0) and start the application the entries doesn't appears on view. I had copy the database to the StreamingAssets Folder under the Folder Assets. But it doesn't work. I don't know what I can do.
    Here is the code:

    Code (CSharp):
    1. public void SetDBPath()
    2.     {
    3.         string DatabaseName = "HighscoreDB.sqlite";
    4.  
    5.         #if UNITY_EDITOR
    6.                 var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
    7.         #else
    8.                 // check if file exists in Application.persistentDataPath
    9.                 var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);
    10.      
    11.                 if (!File.Exists(filepath))
    12.                 {
    13.                     Debug.Log("Database not in Persistent path");
    14.                     // if it doesn't ->
    15.                     // open StreamingAssets directory and load the db ->
    16.          
    17.                     #if UNITY_ANDROID
    18.                                     var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
    19.                                     while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
    20.                                     // then save to Application.persistentDataPath
    21.                                     File.WriteAllBytes(filepath, loadDb.bytes);
    22.                     #elif UNITY_IOS
    23.                                     var loadDb = Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
    24.                                     // then save to Application.persistentDataPath
    25.                                     File.Copy(loadDb, filepath);
    26.                     #elif UNITY_WP8
    27.                                     var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
    28.                                     // then save to Application.persistentDataPath
    29.                                     File.Copy(loadDb, filepath);
    30.          
    31.                     #elif UNITY_WINRT
    32.                                     var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
    33.                                     // then save to Application.persistentDataPath
    34.                                     File.Copy(loadDb, filepath);
    35.                     #endif
    36.          
    37.                                     Debug.Log("Database written");
    38.                 }
    39.      
    40.                 var dbPath = filepath;
    41.         #endif
    42.  
    43.         connectionString = "URI=file:" + dbPath;
    44. }
    45.  
    46. ...
    47.  
    48.  
    49.     private void GetScores()
    50.     {
    51.         using (IDbConnection dbConnection = new SqliteConnection(connectionString))
    52.         {
    53.             dbConnection.Open();
    54.  
    55.             using (IDbCommand dbCmd = dbConnection.CreateCommand())
    56.             {
    57.                 string sqlQuery = "SELECT * FROM HighscoresGame1";
    58.  
    59.                 dbCmd.CommandText = sqlQuery;
    60.  
    61.                 using (IDataReader reader = dbCmd.ExecuteReader())
    62.                 {
    63.                     while (reader.Read())
    64.                     {
    65.                         highScores.Add(new HighScoreNew(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2)));
    66.                     }
    67.  
    68.                     dbConnection.Close();
    69.                     reader.Close();
    70.                 }
    71.             }
    72.         }
    73.         highScores.Sort();
    74.     }
    75.  
    76. ...
    77.  
     
  35. elduderinoU3

    elduderinoU3

    Joined:
    Jul 8, 2017
    Posts:
    2
    Ok, it works.

    I changed in the Player settings the writePermission under the Android Label to External (SD Card)

    ;-)
     
  36. martinandredill

    martinandredill

    Joined:
    Feb 27, 2016
    Posts:
    1
    that is the only code that works!
     
  37. Ace881

    Ace881

    Joined:
    Oct 14, 2017
    Posts:
    1
    Hi, sorry can you give me the code? I tryed your solution but on Unity I can show all my entries from database in the game view, but when I build an apk and copy it to android it no work. Can you help me?
    PS. Your "Plugins" folder is composed by "Android" , "x64" , "x86" folder or only "Android" ?
     
    Last edited: Oct 17, 2017
  38. ivanrouman

    ivanrouman

    Joined:
    Jan 6, 2018
    Posts:
    1
  39. mykzgonzalez

    mykzgonzalez

    Joined:
    Feb 20, 2018
    Posts:
    8
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System;
    5. using System.Data;
    6. using Mono.Data.Sqlite;
    7. using UnityEngine.UI;
    8. using System.IO;
    9.  
    10. public class DBManager : MonoBehaviour
    11. {
    12.  
    13.     //string filepath = Application.persistentDataPath + "/HighScoreDB.sqlite";
    14.     //private string connString;
    15.     public int topRank;
    16.     private List<HighScores> highscores = new List<HighScores>();
    17.     public Transform scoreParent;
    18.     public GameObject scorePrefab;
    19.     public int saveScores;
    20.     public InputField EnterNames;
    21.     public GameObject nameDialog;
    22.     private string connection;
    23.     public string connectionString;
    24.     void Start()
    25.     {
    26.         SetDBPath();
    27.         //connString = "URI=file:" + Application.dataPath + "/HighScoreDB.sqlite";
    28.         deleteExtraScores();
    29.         //AddScore("Test",350);
    30.         showScores();
    31.         //Debug.Log(connString);
    32.     }
    33.  
    34.     void Update()
    35.     {
    36.         if (Input.GetKeyDown(KeyCode.Escape))
    37.         {
    38.             nameDialog.SetActive(!nameDialog.activeSelf);
    39.         }
    40.     }
    41.  
    42.     public void SetDBPath()
    43.     {
    44.         string DatabaseName = "HighScoreDB.sqlite";
    45.  
    46.  
    47. #if UNITY_EDITOR
    48.         var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
    49. #else
    50.                 // check if file exists in Application.persistentDataPath
    51.                 var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);
    52.  
    53.        if (!File.Exists(filepath))
    54.                 {
    55.                     Debug.Log("Database not in Persistent path");
    56.                     // if it doesn't ->
    57.                     // open StreamingAssets directory and load the db ->
    58.        
    59. #if UNITY_ANDROID
    60.                                     var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
    61.                                     while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
    62.                                     // then save to Application.persistentDataPath
    63.                                     File.WriteAllBytes(filepath, loadDb.bytes);
    64. #endif
    65.        
    66.                                     Debug.Log("Database written");
    67.           }
    68.              var dbPath = filepath;
    69. #endif
    70.  
    71.         connectionString = "URI=file:" + dbPath;
    72.     }
    73.  
    74.  
    75.  
    76.     public void enterName()
    77.     {
    78.         if(EnterNames.text != string.Empty)
    79.         {
    80.             int score = UnityEngine.Random.Range(1,1000);
    81.             AddScore(EnterNames.text, score);
    82.             EnterNames.text = string.Empty;
    83.  
    84.             showScores();
    85.         }
    86.     }
    87.  
    88.     private void GetScore()
    89.     {
    90.  
    91.         highscores.Clear();
    92.         using (IDbConnection dbConnection = new SqliteConnection(connectionString))
    93.         {
    94.             dbConnection.Open();
    95.  
    96.             using (IDbCommand dbCmd = dbConnection.CreateCommand())
    97.             {
    98.                 string sqlQuery = "SELECT * FROM Highscores";
    99.  
    100.                 dbCmd.CommandText = sqlQuery;
    101.  
    102.                 using (IDataReader reader = dbCmd.ExecuteReader())
    103.                 {
    104.                     while (reader.Read())
    105.                     {
    106.                         highscores.Add(new HighScores(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2), reader.GetDateTime(3)));
    107.                     }
    108.                     dbConnection.Close();
    109.                     reader.Close();
    110.                 }
    111.             }
    112.         }
    113.         highscores.Sort();
    114.     }
    115.  
    116.     private void AddScore(string pName,int pScore)
    117.     {
    118.         GetScore();
    119.         int hsCount = highscores.Count;
    120.  
    121.         if (highscores.Count >0)
    122.         {
    123.             HighScores lowestScore = highscores[highscores.Count -1];
    124.             if (lowestScore != null && saveScores >0 && highscores.Count >= saveScores && pScore > lowestScore.Scores)
    125.             {
    126.                 DeleteScore(lowestScore.IDS);
    127.                 hsCount--;
    128.             }
    129.         }
    130.  
    131.         if (hsCount < saveScores)
    132.         {
    133.             using (IDbConnection dbConnection = new SqliteConnection(connectionString))
    134.             {
    135.                 dbConnection.Open();
    136.  
    137.                 using (IDbCommand dbCmd = dbConnection.CreateCommand())
    138.                 {
    139.                     string sqlQuery = String.Format("INSERT INTO Highscores(PlayerName,HighScore) VALUES(\"{0}\", \"{1}\"); ", pName, pScore);
    140.  
    141.                     dbCmd.CommandText = sqlQuery;
    142.                     dbCmd.ExecuteScalar();
    143.  
    144.                     dbConnection.Close();
    145.                 }
    146.             }
    147.         }
    148.     }
    149.  
    150.     private void DeleteScore(int pID)
    151.     {
    152.         using (IDbConnection dbConnection = new SqliteConnection(connectionString))
    153.         {
    154.             dbConnection.Open();
    155.  
    156.             using (IDbCommand dbCmd = dbConnection.CreateCommand())
    157.             {
    158.                 string sqlQuery = String.Format("DELETE FROM Highscores WHERE PlayerID = \"{0} \"", pID);
    159.  
    160.                 dbCmd.CommandText = sqlQuery;
    161.                 dbCmd.ExecuteScalar();
    162.  
    163.                 dbConnection.Close();
    164.             }
    165.         }
    166.     }
    167.  
    168.     private void showScores()
    169.     {
    170.         GetScore();
    171.  
    172.         foreach (GameObject score in GameObject.FindGameObjectsWithTag("Score"))
    173.         {
    174.             Destroy(score);
    175.         }
    176.  
    177.         for (int i =0; i < topRank; i++)
    178.         {
    179.             if( i  <= highscores.Count - 1)
    180.             {
    181.             GameObject tmpObject = Instantiate(scorePrefab);
    182.  
    183.             HighScores tmpScore = highscores[i];
    184.  
    185.             tmpObject.GetComponent<HighScoreScript>().setScore(tmpScore.Names, tmpScore.Scores.ToString(), "#" + (i + 1).ToString());
    186.  
    187.             tmpObject.transform.SetParent(scoreParent);
    188.  
    189.             }
    190.         }
    191.     }
    192.  
    193.     private void deleteExtraScores()
    194.     {
    195.         GetScore();
    196.         if (saveScores <= highscores.Count)
    197.         {
    198.             int deleteCount = highscores.Count - saveScores;
    199.  
    200.             highscores.Reverse();
    201.  
    202.             using (IDbConnection dbConnection = new SqliteConnection(connectionString))
    203.             {
    204.                 dbConnection.Open();
    205.  
    206.                 using (IDbCommand dbCmd = dbConnection.CreateCommand())
    207.                 {
    208.                     for (int i = 0; i < deleteCount; i++)
    209.                     {
    210.                         string sqlQuery = String.Format("DELETE FROM Highscores WHERE PlayerID = \"{0} \"", highscores[i].IDS);
    211.  
    212.                         dbCmd.CommandText = sqlQuery;
    213.                         dbCmd.ExecuteScalar();
    214.                     }
    215.                     dbConnection.Close();
    216.                 }
    217.             }
    218.         }
    219.     }
    220. }
    221.  
    I need your help guys.. everything works fine on my PC and even in my Android Unity Remote 5 but when I'm trying to upload the game as an apk, the database does not Load.. There are no errors so I'm getting really confused.

    Please help. Thank you :D
     
  40. mykzgonzalez

    mykzgonzalez

    Joined:
    Feb 20, 2018
    Posts:
    8
    I've also tried the Write Protection to External SD but still does not work for me :(
     
  41. Doucky

    Doucky

    Joined:
    Jan 19, 2017
    Posts:
    3
    Hello, Thank's for this post is helped me so much during several months.

    I have :
    - Create Plugins folder and place into it following files : "Mono.Data.Sqlite.dll" "sqlite3.dll" "System.Data.dll" "sqlite3.def"
    - Create Plugins/Android folder and place into it : "libsqlite3.so"
    - Modify settings from .Net2.0 subset to .Net2.0 in player preference

    And that work !
    Now, I have upgraded my phone from Android 7.0 to Android 8.0 and that work no more..

    I tried :
    - Write Protection to External SD
    - Modify Minimum API lvl from LVL 16 to LVL23
    - Modify import setting of libsqlite3.so to ARM64 (I have a Samsung Galaxy S7)
    - Create different folder in Plugins/Android/libs like /x86 or /armeabi-v7a or /arm64-v8a and place into it the libsqlite3.so with the adapted import setting
    - Compile the source code of sqlite for create my own libsqlite3.so (but I have abandonned)
    - Find a way to autorize all permission in the AndroidManifest file (but I have abandonned)

    On the smartPhone of a friend (Samsung Galaxy S6 Android 7.0) all works fine..

    Someone could help me please ?

    The error is the following :
    System.DllNotFoundException : sqlite3 at (wrapper managed-to-native)
    Mono.Data.Sqlite.Unsafe.NativeMethods:sqlite3_open_v2 (byte[],inptr&,int,intptr)
    at Mono.Data.Sqlite.SQLite3.Open (System.String strFilename, SQLiteOpenFlagsEnum Flags, Int32 maxPoolSize, Boolean usePool) [0x00000] in <filename unknown>:0
    at Mono.Data.SqliteConnection.Open () [0x00000] in <filename unknown>:0
    at BaseDeDonne.Connection () [0x00000] in <filename unknown>:0
     
  42. alexikari

    alexikari

    Joined:
    Aug 31, 2015
    Posts:
    21
    Hi! Did you find the solution? I have the same problems and until now i do not find the solution.
     
  43. unity_l3Ac7R_V3zAEkQ

    unity_l3Ac7R_V3zAEkQ

    Joined:
    Jul 27, 2018
    Posts:
    9
    Hi, i am new one in unity. i need to connect Sqlite database in Android Device. in unity Editor is Working fine but Android device i am getting error ="Connection string format is invalid" ... here is my code. kindly help anyone

    Code (CSharp):
    1.  
    2.         try
    3.         {
    4.          
    5.             if (Application.platform != RuntimePlatform.Android)
    6.             {
    7.  
    8.                 connection = Application.dataPath + "/StreamingAssets/Database.db";
    9.  
    10.                 if (!File.Exists(connection))
    11.                 {
    12.                     File.Create(connection);
    13.                 }
    14.                 connection = "URI=file:" + connection;
    15.  
    16.             }
    17.             else
    18.             {
    19.                 connection = Application.persistentDataPath + "/absdb.s3db";
    20.  
    21.                 if (!File.Exists(connection))
    22.                 {
    23.  
    24.                     // if it doesn't ->
    25.  
    26.                     // open StreamingAssets directory and load the db ->
    27.  
    28.                     WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/absdb.s3db");  // this is the path to your StreamingAssets in android
    29.  
    30.                     while (!loadDB.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
    31.  
    32.                     // then save to Application.persistentDataPath
    33.  
    34.                    
    35.                     File.WriteAllBytes(connection, loadDB.bytes);
    36.                  
    37.                 }
    38.             }
    39.             SqliteConnection con = new SqliteConnection(connection);
    40.             con.Open();
    41.             SqliteCommand CreateLifecmd= new SqliteCommand("CREATE TABLE Lifes( id INTEGER PRIMARY KEY AUTOINCREMENT,Lifes INTEGER not null); ",con);
    42.             CreateLifecmd.ExecuteNonQuery();
    43.  
    44.             SqliteCommand CreateLevelscmd = new SqliteCommand("CREATE TABLE Levels( id INTEGER PRIMARY KEY AUTOINCREMENT,UnlockLevels INTEGER not null); ", con);
    45.             CreateLevelscmd.ExecuteNonQuery();
    46.  
    47.             SqliteCommand insertLifecmd = new SqliteCommand("INSERT INTO  Lifes (Lifes) Values (2)", con);
    48.             insertLifecmd.ExecuteNonQuery();
    49.  
    50.             SqliteCommand InsertLevelscmd = new SqliteCommand("INSERT INTO  Levels (UnlockLevels) Values (1)", con);
    51.             InsertLevelscmd.ExecuteNonQuery();
    52.             con.Open();
    53.          
    54.          
    55.         }
    56.         catch(Exception ex)
    57.         {
    58.             UiTExt.text = connection + "----" + ex.Message;
    59.         }
    60.  
     
  44. des666sar

    des666sar

    Joined:
    Dec 12, 2016
    Posts:
    1
    The author of the post - God!
    Without exaggeration. I suffered with a F***ing SQLite for a week. Only after reading this post everything works fine. Thank you very much!!!
     
  45. bibalexwalid

    bibalexwalid

    Joined:
    Mar 28, 2019
    Posts:
    2
    Tutorial SQLite Unity3d 2018 or hegher( Android , Windows Phone , Windows , IOS, WINRT )
    How to Connection Database Sqlite how to Create Table , Select , Insert , Update , Delete , Search

    How to read data from on unity Solving all error in unity for assembly reference:
    1- error "The type or namespace name Data' does not exist in the namespace 'Mono'. Are you missing an assembly reference?"
    2- and error "The type or namespace name MONO' does not exist in the namespace Data'. Are you missing an assembly reference?"
    - using Mono.Data.Sqlite;
    - using System;
    - using System.Data;
    - using System.IO;
    - using UnityEngine.UI;

    learning how:
    * SQLite Admin to create database and tables .......
    * SQLite DLL to support unity .s3db extension and compile on unity for windows 32bit or 64bit.

    Github example :https://github.com/walidabazo/SQLiteUnity3d_Android
     
    Last edited: Apr 15, 2019
  46. Lutfullah

    Lutfullah

    Joined:
    Jan 24, 2017
    Posts:
    1
    Thanks for the very helpful post