Unity 3D + Android + SQLite Examples English Sign in Home Unity Industries Showcase Asset Store Learn Community Download Buy Unity 3D + Android + SQLite Examples fruki New Member 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 runtimeThis 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): private IDbConnection dbcon; … public void OpenDB(string p) { connection = “URI=file:” + Application.persistentDataPath + “/” + p; // we set the connection to our database //connection = “URI=file:” + p; // like this will NOT work on android Debug.Log(connection); dbcon = new SqliteConnection(connection); dbcon.Open(); } 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 deviceThis 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): // check if file exists in Application.persistentDataPath string filepath = Application.persistentDataPath + “/” + p; if(!File.Exists(filepath)) { // if it doesn’t -> // open StreamingAssets directory and load the db -> WWW loadDB = new WWW(“jar:file://” + Application.dataPath + “!/assets/” + p); // this is the path to your StreamingAssets in android while(!loadDB.isDone) {} // CAREFUL here, for safety reasons you shouldn’t let this while loop unattended, // place a timer and error check // then save to Application.persistentDataPath File.WriteAllBytes(filepath, loadDB.bytes); } //open db connection connection = “URI=file:” + filepath; dbcon = new SqliteConnection(connection); dbcon.Open(); 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: $SQLiteLoad.unitypackage File size: 984.2 KB Views: 2,626 $SQLite.unitypackage File size: 981.4 KB Views: 2,063 Last edited: Dec 7, 2011 Dec 7, 2011 mpavlinsky New Member 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. Jan 30, 2012 MonoSapiens New Member If you don’t wish to have your work mixed up with non-professional solutions, you can try this asset:http://u3d.as/content/mono-sapiens-ltda/mono-sqlite/2QwI’m using it and it really solves my problems. Apr 17, 2012 Meltdown Member 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_nameYour SQLLiteLoad Package works fine on the Android device.Yet my own database doesn’t. Any idea what could be causing this issue? Jul 19, 2012 Fayer New Member 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? Sep 7, 2012 Oksana Iashchuk Member please, check this ->http://u3d.as/content/orange-tree/sqlite-kit/3kaThat 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 Sep 10, 2012 ina Member How does this compare to MonoSapiens? MonoSQLite Sep 11, 2012 Oksana Iashchuk Member If you like I could sent an example code to you. You will find how easy work with database byhttp://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 Sep 11, 2012 liliyanlyn New Member 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. Jan 20, 2013 Compguru910 New Member 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 appCreate 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. May 28, 2013 tredpro Member Im sorry but what area to you past the url to your database? Dec 8, 2013 hollym16 Member 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? Feb 25, 2014 joao_pm New Member Thanks!This post was really useful for me, almost 3 years after it was written! Apr 17, 2014 kannan_unity3d Member i am currently working on tis.thanks guys Aug 13, 2014 ganesh Member 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 waykp word value1 bio poa2 primary pob3 primary pos Code (CSharp): string[,] result2 = SingleSelectWhere(“petdef”, “value”, “word”, “=”, “‘primary'”); // Concatenate all the elements into a StringBuilder. builderdisplay = new StringBuilder(); for (int i = 0; i < result2.GetLength(0); i++) { for (int j = 0; j < result2.GetLength(1); j++) { builderdisplay[2].Append(result2[i,j]); builderdisplay[2].Append(‘ ‘); } subjectnamed.text = builderdisplay.ToString (); } Sep 19, 2014 ganesh Member how to add and access one more field in $SQLite.unitypackage.Any idea about that. Sep 19, 2014 Simball Member 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? Sep 22, 2014 Meltdown Member 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. Sep 22, 2014 thready Member 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: errors.png File size: 56.1 KB Views: 37 Sep 23, 2014 monching21 Member me also, it looks like unity free version does not support the sqlliteclient T_T or im wrong T_T pls help us Sep 28, 2014 (You must log in or sign up to reply here.) Posted on 2014-11-03 8:20 PM by andrew Comment 📂This entry was posted in UNITY3D/COCOS2D 참고를 위한 저장물 📎and tagged c# sqlite unity3d
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 runtimeThis 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): private IDbConnection dbcon; … public void OpenDB(string p) { connection = “URI=file:” + Application.persistentDataPath + “/” + p; // we set the connection to our database //connection = “URI=file:” + p; // like this will NOT work on android Debug.Log(connection); dbcon = new SqliteConnection(connection); dbcon.Open(); } 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 deviceThis 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): // check if file exists in Application.persistentDataPath string filepath = Application.persistentDataPath + “/” + p; if(!File.Exists(filepath)) { // if it doesn’t -> // open StreamingAssets directory and load the db -> WWW loadDB = new WWW(“jar:file://” + Application.dataPath + “!/assets/” + p); // this is the path to your StreamingAssets in android while(!loadDB.isDone) {} // CAREFUL here, for safety reasons you shouldn’t let this while loop unattended, // place a timer and error check // then save to Application.persistentDataPath File.WriteAllBytes(filepath, loadDB.bytes); } //open db connection connection = “URI=file:” + filepath; dbcon = new SqliteConnection(connection); dbcon.Open(); 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
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.
If you don’t wish to have your work mixed up with non-professional solutions, you can try this asset:http://u3d.as/content/mono-sapiens-ltda/mono-sqlite/2QwI’m using it and it really solves my problems.
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_nameYour SQLLiteLoad Package works fine on the Android device.Yet my own database doesn’t. Any idea what could be causing this issue?
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?
please, check this ->http://u3d.as/content/orange-tree/sqlite-kit/3kaThat 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
If you like I could sent an example code to you. You will find how easy work with database byhttp://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();
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.
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 appCreate 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.
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?
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 waykp word value1 bio poa2 primary pob3 primary pos Code (CSharp): string[,] result2 = SingleSelectWhere(“petdef”, “value”, “word”, “=”, “‘primary'”); // Concatenate all the elements into a StringBuilder. builderdisplay = new StringBuilder(); for (int i = 0; i < result2.GetLength(0); i++) { for (int j = 0; j < result2.GetLength(1); j++) { builderdisplay[2].Append(result2[i,j]); builderdisplay[2].Append(‘ ‘); } subjectnamed.text = builderdisplay.ToString (); }
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?
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.
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!
me also, it looks like unity free version does not support the sqlliteclient T_T or im wrong T_T pls help us