Hi everyone, I needed to get an SQLite database to run on Ipad/Iphone/Mac standalone and Windows standalone. Searching in the Forum I only found some kind of old statements which did not run at all. Most of the Example work with System.Data.dll which Unity cannot compile at all (maybe I was only an Idiot, you never know). I was always getting an ArgumentException. I will now post a solution which will work with the variants mentioned above. The only thing which is not so nice, is that you have to copy the Database to the Application.datapath by hand. If somebody has a better solution for that he is free to post so. You only need two dlls. You have to copy both to the Plugins-Folder in Unity: sqlite3.dll Mono.Data.Sqlite.dll Here is the code for the Connection: ------------------------------------------------------ using UnityEngine; using System; using Mono.Data.Sqlite; public class dbController : MonoBehaviour { protected SqliteConnection dbconn; void Awake () { if (Application.platform == RuntimePlatform.IPhonePlayer) { dbconn = new SqliteConnection("URI=file:" +Application.dataPath + "/../Data.db"); } else { dbconn = new SqliteConnection("URI=file:" +Application.dataPath + "/Data.db"); } dbconn.Open(); try { SqliteCommand cmd = new SqliteCommand("SELECT firstname, lastname FROM adressbook", dbconn); SqliteDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while(reader.Read()) { string FirstName = reader.GetString (0); string LastName = reader.GetString (1); Debug.Log ( FirstName + LastName ); } } reader.Close(); reader = null; } catch { Debug.Log("Error reading DB"); } cmd.Dispose(); cmd = null; dbconn.Close(); dbconn = null; } } ------------------------------------------------ So now I tell you where to put the Data.db file so it works for serveral cases: 1. Unity Editor: Place de db in the Project/Assets Folder (this stays you don't have to change any more) 2. Unity Windows: After every Build you have to place the db in the {Name}_Data Folder 3. Ipad/Iphone: After the Build you have to add the fille to XCode: - XCode "File" -> Add Files to "...." -> Select db Then the db-File must be located in the first layer 4. Mac Standalone: Create app. Open Finder. Rightclick on app and select "Show package content" and add the db in the "Contents"-Folder So I hope you don't need search the whole WWW any more.
Hi! First of all, I wanted to thank you so much for sharing this code here on the forum! Second, I was wondering if you might be able to spend a bit of time and post your code (and maybe an example script that uses it)? I know it's a lot to ask - I put together a JavaScript tutorial on how to get SQLite working there, so I understand if you don't want to commit to the time required. But let me know if you'd be willing to do it! http://www.unifycommunity.com/wiki/index.php?title=SQLite
if you want a strong solution to store data locally take a look here: http://siaqodb.com/?p=482 (full disclosure- I'm involved in project), but we really see Unity3D developers need a solution that just works. Put dll in your scripts folder and use it, that's all!
Hi, I did excatly as you posted but I am getting the following error when I make a windows build (the game runs fine in the editor): Is it possible that I am getting this error because I am using Unity Basic and not Unity Pro? I have looked at tons of other topcs on the forums, but this is the most recent. I have tried most of the other fixes that I have seen but nothing seems to work. Did you run into this problem at all when you were getting this solution to work? Thanks
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 )..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): using UnityEngine; using System.Collections; using System; /// <summary> /// Entity class of Customer /// Mapped manually (!!!) from SampleDB /// </summary> public class CustomerEntity { #region Fields private int iD; private string userName; #endregion #region Properties /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public int ID { get { return iD; } set { iD = value; } } /// <summary> /// Gets or sets the name of the user. /// </summary> /// <value> /// The name of the user. /// </value> public string UserName { get { return userName; } set { userName = value; } } /// <summary> /// Prevents a default instance of the <see cref="CustomerEntity"/> class from being created. /// </summary> private CustomerEntity() { } /// <summary> /// Initializes a new instance of the <see cref="CustomerEntity"/> class. /// </summary> /// <param name="iD">The identifier</param> /// <param name="userName">Name of the user.</param> public CustomerEntity(int iD, string userName) { if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("userName cannot be null or empty !"); this.iD = iD; this.userName = userName; } #endregion } "Class CustomerEntityHelper " Code (CSharp): using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Data; using Mono.Data.Sqlite; using System; /// <summary> /// CustomerEntityHelper Help you to retrieve the named Entity /// </summary> public class CustomerEntityHelper : DBHelper { public List<CustomerEntity> GetAllCustomers() { List<CustomerEntity> result = new List<CustomerEntity>(); try { using (IDbConnection dbcon = new SqliteConnection(base.ConnString) as IDbConnection) { dbcon.Open(); IDbCommand dbcmd = dbcon.CreateCommand(); dbcmd.CommandText = "SELECT ID, UserName FROM Customer"; ; using (IDataReader reader = dbcmd.ExecuteReader()) { while (reader.Read()) { int id = reader.GetInt32(0); string userName = reader.GetString(1); CustomerEntity customer = new CustomerEntity(id, userName); result.Add(customer); } reader.Close(); } dbcon.Close(); } } catch (Exception ex) { Debug.LogError("GetAllCustomers thrown an error : " + ex.ToString()); } return result; } } "Class ConnectionResult" Code (CSharp): using UnityEngine; using System.Collections; /// <summary> /// ConnectionResult /// </summary> public class ConnectionResult { /// <summary> /// ConnectionStatus /// </summary> public enum ConnectionStatus { Connected, NotConnected } private string connectionStringUsed; private string errorMessage; private ConnectionStatus status; public ConnectionStatus Status { get { return status; } set { status = value; } } public string ConnectionStringUsed { get { return connectionStringUsed; } set { connectionStringUsed = value; } } public string ErrorMessage { get { return errorMessage; } set { errorMessage = value; } } } "Class DBHelper" Code (CSharp): using UnityEngine; using System.Collections; using System; using System.Data; using Mono.Data.Sqlite; using System.IO; /// <summary> /// DBHelper /// </summary> public class DBHelper { #region Fields private string connString; private string databaseCompletePath;//the path in your Unity Project and the DB Name #endregion #region Properties /// <summary> /// Gets the connection string. /// </summary> /// <value> /// The connection string. /// </value> public string ConnString { get { return connString; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DBHelper"/> class. /// </summary>s public DBHelper() { this.databaseCompletePath = "/SampleDB"; this.connString = string.Format("URI=file:{0}{1}", Application.dataPath,this. databaseCompletePath); } /// <summary> /// Initializes a new instance of the <see cref="DBHelper"/> class. /// </summary> /// <param name="specificConnectionString">The specific connection string.</param> /// <example>connection string could be: YourFloder1/Yourfolder2/YourDBName</example> public DBHelper(string specificConnectionString) { this.databaseCompletePath = specificConnectionString; this.connString = string.Format("URI=file:{0}/{1}",Application.dataPath,specificConnectionString); } #endregion #region Methods /// <summary> /// Checks the connection. /// </summary> /// <returns></returns> public ConnectionResult CheckConnection() { ConnectionResult result = new ConnectionResult(); result.ConnectionStringUsed = this.connString; try { using (IDbConnection dbcon = new SqliteConnection(this.connString) as IDbConnection) { //check if db file exist (with a bad name, sqlite try to create the DB and we don't want this behavior!) if (File.Exists(string.Format("{0}{1}", Application.dataPath,this.databaseCompletePath))) { dbcon.Open(); //Open connection to the database. result.Status = ConnectionResult.ConnectionStatus.Connected; dbcon.Close(); } else throw new Exception("Database was not Found !"); } } catch (Exception ex) { result.ErrorMessage = ex.ToString(); result.Status = ConnectionResult.ConnectionStatus.NotConnected; } return result; } #endregion } "Class SampleDB" Code (CSharp): using UnityEngine; using System.Collections; using System.Text; using System; public class SampleDB : MonoBehaviour { private DBHelper dbHelper; private bool isDBConnected; private string checkResultMessage; private string customerMessage; /// <summary> /// Starts this instance. /// </summary> void Start() { this.checkResultMessage = string.Empty; this.dbHelper = new DBHelper();//use the embedded DBHelper connection string. this.isDBConnected = false; // before check, we consider the DB status as not connected. } void OnGUI() { int heightLocation = 100; //used for GUI StringBuilder sbCustomer = new StringBuilder();// used to add string if (GUI.Button(new Rect(10, 10, 200, 30), "Check Connection")) { checkResultMessage = string.Empty; ConnectionResult result = this.dbHelper.CheckConnection(); this.isDBConnected = (result.Status == ConnectionResult.ConnectionStatus.Connected); checkResultMessage = (result.Status == ConnectionResult.ConnectionStatus.Connected) ? string.Format("Connection OK with connection string {0}", result.ConnectionStringUsed) : string.Format("Connection ERROR: {0}",result.ErrorMessage) ; } GUI.Label(new Rect(10, 50, 600, 60), checkResultMessage); if (this.isDBConnected) { if (GUI.Button(new Rect(220, 10, 200, 30), "Get customers")) { CustomerEntityHelper customerHelper = new CustomerEntityHelper(); foreach (CustomerEntity customer in customerHelper.GetAllCustomers()) { sbCustomer.Append(string.Format("{0} - ID: {1}{2}", customer.UserName, customer.ID,Environment.NewLine)); heightLocation += 40; } this.customerMessage = sbCustomer.ToString(); } } GUI.Label(new Rect(10, 50, 600, 60), checkResultMessage); GUI.Label(new Rect(10, 10 + heightLocation, 300, 600), this.customerMessage); } } BTW: I am new in the Forum and That's my first post,sorry for my bad english .Thank you even for reading this whole stuff