Unity Community

Register or Sign In:

+ Reply to Thread
Results 1 to 20 of 20

  1. Posts
    80

    SQLite Class - Easier Database Stuff

    Hello, I thought I would share my basic Sqlite class for those who are interesting in learning how to use unity with it or those who are looking to implement something similar.

    This will help create cleaner code for those who need to use databases.
    Ultimately I want to create an editor tool for database so that we can have another tool on top of Unity's awesome-ness.

    "Update - 8/14 I added a Create Table Function"
    "Update - 8/14 I added a Insert Functions"

    The Class
    Code:  
    1. import          System.Data;  // we import our  data class
    2. import          Mono.Data.SqliteClient; // we import our sqlite client
    3.  
    4. class dbAccess {
    5.     // variables for basic query access
    6.     private var connection : String;
    7.     private var dbcon : IDbConnection;
    8.     private var dbcmd : IDbCommand;
    9.     private var reader : IDataReader;
    10.    
    11.     function OpenDB(p : String){
    12.     connection = "URI=file:" + p; // we set the connection to our database
    13.     dbcon = new SqliteConnection(connection);
    14.     dbcon.Open();
    15.     }
    16.    
    17.     function BasicQuery(q : String, r : boolean){ // run a baic Sqlite query
    18.         dbcmd = dbcon.CreateCommand(); // create empty command
    19.         dbcmd.CommandText = q; // fill the command
    20.         reader = dbcmd.ExecuteReader(); // execute command which returns a reader
    21.         if(r){ // if we want to return the reader
    22.         return reader; // return the reader
    23.         }
    24.     }
    25.    
    26.     function CreateTable(name : String, col : Array, colType : Array){ // Create a table, name, column array, column type array
    27.         var query : String;
    28.         query  = "CREATE TABLE " + name + "(" + col[0] + " " + colType[0];
    29.         for(var i=1; i<col.length; i++){
    30.             query += ", " + col[i] + " " + colType[i];
    31.         }
    32.         query += ")";
    33.         dbcmd = dbcon.CreateCommand(); // create empty command
    34.         dbcmd.CommandText = query; // fill the command
    35.         reader = dbcmd.ExecuteReader(); // execute command which returns a reader
    36.    
    37.     }
    38.    
    39.     function InsertIntoSingle(tableName : String, colName : String, value : String){ // single insert
    40.         var query : String;
    41.         query = "INSERT INTO " + tableName + "(" + colName + ") " + "VALUES (" + value + ")";
    42.         dbcmd = dbcon.CreateCommand(); // create empty command
    43.         dbcmd.CommandText = query; // fill the command
    44.         reader = dbcmd.ExecuteReader(); // execute command which returns a reader
    45.     }
    46.    
    47.     function InsertIntoSpecific(tableName : String, col : Array, values : Array){ // Specific insert with col and values
    48.         var query : String;
    49.         query = "INSERT INTO " + tableName + "(" + col[0];
    50.         for(var i=1; i<col.length; i++){
    51.             query += ", " + col[i];
    52.         }
    53.         query += ") VALUES (" + values[0];
    54.         for(i=1; i<values.length; i++){
    55.             query += ", " + values[i];
    56.         }
    57.         query += ")";
    58.         dbcmd = dbcon.CreateCommand();
    59.         dbcmd.CommandText = query;
    60.         reader = dbcmd.ExecuteReader();
    61.     }
    62.    
    63.     function InsertInto(tableName : String, values : Array){ // basic Insert with just values
    64.         var query : String;
    65.         query = "INSERT INTO " + tableName + " VALUES (" + values[0];
    66.         for(var i=1; i<values.length; i++){
    67.             query += ", " + values[i];
    68.         }
    69.         query += ")";
    70.         dbcmd = dbcon.CreateCommand();
    71.         dbcmd.CommandText = query;
    72.         reader = dbcmd.ExecuteReader();
    73.     }
    74.    
    75.     function SingleSelectWhere(tableName : String, itemToSelect : String, wCol : String, wPar : String, wValue : String){ // Selects a single Item
    76.         var query : String;
    77.         query = "SELECT " + itemToSelect + " FROM " + tableName + " WHERE " + wCol + wPar + wValue; 
    78.         dbcmd = dbcon.CreateCommand();
    79.         dbcmd.CommandText = query;
    80.         reader = dbcmd.ExecuteReader();
    81.         var readArray = new Array();
    82.         while(reader.Read()){
    83.             readArray.Push(reader.GetString(0)); // Fill array with all matches
    84.         }
    85.         return readArray; // return matches
    86.     }
    87.  
    88.    
    89.     function CloseDB(){
    90.         reader.Close(); // clean everything up
    91.         reader = null;
    92.         dbcmd.Dispose();
    93.         dbcmd = null;
    94.         dbcon.Close();
    95.         dbcon = null;
    96.     }
    97.    
    98. }
    An Example of Creating a Table
    You can create two arrays, one being the column headers, and another being the data types.
    Code:  
    1. var db : dbAccess;
    2. function Start(){
    3.     db = new dbAccess();
    4.     db.OpenDB("myDB.sqdb");
    5.     var tableName = "myTable";
    6.     var columnNames = new Array("firstName","lastName");
    7.     var columnValues = new Array("text","text");
    8.     db.CreateTable(tableName,columnNames,columnValues);
    9.     db.CloseDB();
    10. }
    An Example of Easy Insert
    This example is an easy way to add a single record
    Code:  
    1. var db : dbAccess;
    2. function Start(){
    3.     db = new dbAccess();
    4.     db.OpenDB("myDB.sqdb");
    5.     var tableName = "myTable";
    6.     // IMPORTANT remember to add single ' to any strings, do not add them to numbers!
    7.     var values = new Array("'Bob'","'Sagat'");
    8.     db.InsertInto(tableName, values);
    9.     db.CloseDB();
    10. }
    An Example of Single WHERE select
    I am not done with this class, but this is an example of getting an array of items that match a WHERE clause.
    Code:  
    1. var db : dbAccess;
    2. function Start(){
    3.     db = new dbAccess();
    4.     db.OpenDB("myDB.sqdb");
    5.     var tableName = "myTable";
    6.     // table name, I want to return everyone whose first name is Bob when their last name is = to Sagat, this returs an array
    7.     var resultArray = db.SingleSelectWhere(tableName, "firstName", "lastName","=","'Sagat'"); // Remember the '' on String values
    8.     print(resultArray[0]);
    9.     // of course you can loop through them all if you wish
    10.     db.CloseDB();
    11.    
    12. }


  2. Posts
    1

    Can this code connect to all Databases provider?

    Hi.

    I'm new on the forum, and this is my first question. Sorry about my english, but I'm not English :P

    Well, my question is simple. Can this code connect to all Databases? Can I connect with an Oracle, MSSQL and MySql?

    How can I do this with each one?

    Thx a lot.


  3. Location
    Charlottetown, PEI
    Posts
    108
    To answer the above question, no - SQLite creates a file on the hard drive that ACTS like a database.

    To praise the further above - Thank you so much for providing this, you saved me hours :P


  4. Location
    Schwabsburg
    Posts
    224

    webplayer

    Hi,

    Does this also work with a webplayer build ?
    At least to read data..
    Best GreetinGs
    Timo

    DynamicHead -- An Unity developer.


  5. Location
    India
    Posts
    116
    Can we use this to get the data retrieved from the database and send data to the database. Can anyone suggest a way to get working the basic connection to send a info or data to the database. I am using .Net server and my database is SQL server 2005.
    Pavees,
    India


  6. Location
    Schwabsburg
    Posts
    224
    Do you develop for webplayer or standalone ?


    Btw. looks like sqlite doesn't work with the webplayer.. since you can only access URIs.
    Best GreetinGs
    Timo

    DynamicHead -- An Unity developer.


  7. Posts
    31
    Trying to get this class to work. I am having basic error not sure how to solve.

    Assets/dbAccess.js(1,17): BCE0021: Namespace 'System.Data' not found, maybe you forgot to add an assembly reference?

    What am I missing to get the imports to work?

    Thanks in advance.


  8. Location
    Zürich, Switzerland
    Posts
    25,088
    he imports system.data in the very first script and should work on unity 2.6
    on unity iphone it won't work I think as this relies on stuff thats not present on the iphone even with .net 2.1 enabled, there you would use plugins and use the always present sqlite3 library on the iphone.


    as for SQLite + Webplayer: not possible as you can't access files and filestreams at all there and if it is within the project its not accessable.

    also you would never access a regular webhosted database (oracle, mssql, mysql) this way as you do not want to make wildcard remote accounts for users to directly connect and hack in no time due to the login details being sent over to by them and stored in the client.
    You would instead use client <-> php / asp <-> database


  9. Posts
    31
    Yes I'm trying to use with iPhone.

    The use of plugins is only supported by iPhone Advanced. So there is no way to implement sqlite with iPhone Basic?

    Thanks in advance.


  10. Location
    Zürich, Switzerland
    Posts
    25,088
    See Poor Monkey framework on how to integrate such a thing with iPhone Basic.
    As database lookups aren't high frequency that will work fine.

    the real work is the xcode side implementation for sqlite


  11. Location
    Co Donegal, Ireland
    Posts
    962
    I'm having some crashing issue when app running as a Windows standalone (Windows Vista x64).

    The Database is working fine within the Editor but when built to a Standalone it is crashing sometimes?! 5 times out of 10 it works fine, but the other half it is crashing when it starts up OR when you quit the app?!

    I only have Database calls within Start() methods so maybe it's crashing when SELECTing data and the Database isn't properly connected (i'm only guessing here).

    Anyone else had these issues or can point me in the right direction to correcting them. I'm using the latest sqlite dll from the SQLite website and the frameworks from the Unity Installation.

    Kind Regards,
    Matt.
    Web (paid and free tutorials): http://polypusher.net Twitter: thePolyPusher
    My Blog: http://fearedfuture.blogspot.com/
    Unity / modo tutorials: http://vimeo.com/channels/115146


  12. Location
    Co Donegal, Ireland
    Posts
    962
    Sorry to bump this one.

    I just don't want to design this app too much around a database if it is going to be technically fraught with problems.

    I am using the methods from the top of the thread albeit in C# with a class name change and am just calling this:
    Code:  
    1. void Start() {
    2.    db = new dbController();
    3.    db.OpenDB("CasusBelliDB.sqdb");
    4.  
    5.    List<string> result = new List<string>();
    6.    result = db.SingleSelectWhere("test","name","name","=", "'Matt'"); // Process SQL
    7.  
    8.    guiText.text = result[0];
    9.  
    10.    db.CloseDB(); // Close DB connection
    11. }

    Like i say, when the app doesn't crash everything is working fine. But sometimes it is crashing on app start and sometimes on app closing. Why would the app crash on closing?? Would the problem be the dll conflicting somewhere? It is working 100% in the editor (but then again, the app isnt having to startup or close down there is it)

    Anyway, if anyone has any ideas or has tried SQLite could they let me know. I'll change the app to not use a DB if I can't get this sorted (which will be a shame).

    EDIT: I have made a MAC Intel build and it seems to run 100%. Have started and stopped app about 30 times with no crashes. Windows Vista x64 maybe?? I'll try it on my wife laptop (vista 32 bit).

    EDIT2: Seems to work fine on Vista x86 also... looks like it's Vista x64!... oh dear... maybe i'm being a numpty and have the incorrect dll's... i may have an embarrased face yet!

    Best Regards,
    Matt.
    Web (paid and free tutorials): http://polypusher.net Twitter: thePolyPusher
    My Blog: http://fearedfuture.blogspot.com/
    Unity / modo tutorials: http://vimeo.com/channels/115146


  13. Posts
    20
    fallingbrickwork, were you able to resolve this? i'm seeing similar behavior in windows 7.


  14. Location
    Qc, Canada
    Posts
    40
    Many thanks to dklompmaker.

    You just made my day MUCH easier. Haven't had the chance to put it into action yet but understanding what you do is of great help!

    Just wanted to show some appreciation.


  15. Location
    china,changchun
    Posts
    2
    Hi , i have some question,when i "Build & Run" the project
    ArgumentException: The Assembly System.Configuration is referenced by System. But the dll is not allowed to be included or could not be found.
    UnityEditor.AssemblyHelper.AddReferencedAssemblies Recurse (System.String assemblyPath, System.Collections.Generic.List`1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary`2 cache) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/AssemblyHelper.cs:52)
    UnityEditor.AssemblyHelper.AddReferencedAssemblies Recurse (System.String assemblyPath, System.Collections.Generic.List`1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary`2 cache) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/AssemblyHelper.cs:55)
    UnityEditor.AssemblyHelper.AddReferencedAssemblies Recurse (System.String assemblyPath, System.Collections.Generic.List`1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary`2 cache) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/AssemblyHelper.cs:55)
    UnityEditor.AssemblyHelper.AddReferencedAssemblies Recurse (System.String assemblyPath, System.Collections.Generic.List`1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary`2 cache) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/AssemblyHelper.cs:55)
    UnityEditor.AssemblyHelper.FindAssembliesReference dBy (System.String[] paths, System.String[] foldersToSearch) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/AssemblyHelper.cs:86)
    UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()
    Error building Player: Extracting referenced dlls failed.
    UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()
    Exception: Error building Player: Extracting referenced dlls failed.
    UnityEditor.BuildPlayerWindow.BuildPlayerWithDefau ltSettings (Boolean askForBuildLocation, BuildOptions forceOptions) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/BuildPlayerWindow.cs:341)
    UnityEditor.BuildPlayerWindow.BuildPlayerAndRun () (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/BuildPlayerWindow.cs:263)


  16. Posts
    15
    Hi, if you're trying to get this to work, I've posted a sample project and instructions on the Unify wiki that should get you up and running -
    http://www.unifycommunity.com/wiki/i...p?title=SQLite


  17. Posts
    11

    c# version

    BTW, it looks like working in C#(at least in Pro version which I am using). I've implemented functional from http://www.unifycommunity.com/wiki/i...p?title=SQLite in C#. May need System.Data.dll and Mono.Data.Sqlite.dll (can be found in mono develop libs directory). Here's the code.
    Code:  
    1. using UnityEngine;
    2. using System;
    3. using Mono.Data.Sqlite;
    4.  
    5.  
    6. public class DbAccess
    7. {
    8.     private SqliteConnection dbConnection;
    9.     private SqliteCommand dbCommand;
    10.     private SqliteDataReader reader;
    11.  
    12.  
    13.     /// <summary>
    14.     ///  string to connect. The simpliest one looks like "URI=file:filename.db"
    15.     /// </summary>
    16.     /// <param name="connectionString">
    17.     /// A <see cref="System.String"/>
    18.     /// </param>
    19.     public DbAccess (string connectionString)
    20.     {
    21.         OpenDB (connectionString);
    22.     }
    23.  
    24.     /// <summary>
    25.     ///  The same as <see cref="DbAccess#Dbaccess" / >
    26.     /// </summary>
    27.     /// <param name="connectionString">
    28.     /// A <see cref="System.String"/>
    29.     /// </param>
    30.     public void OpenDB (string connectionString)
    31.     {
    32.         dbConnection = new SqliteConnection (connectionString);
    33.         dbConnection.Open ();
    34.         Debug.Log ("Connected to db");
    35.     }
    36.  
    37.     /// <summary>
    38.     /// Closes connection to db
    39.     /// </summary>
    40.     public void CloseSqlConnection ()
    41.     {
    42.         if (dbCommand != null) {
    43.             dbCommand.Dispose ();
    44.         }
    45.         dbCommand = null;
    46.         if (reader != null) {
    47.             reader.Dispose ();
    48.         }
    49.         reader = null;
    50.         if (dbConnection != null) {
    51.             dbConnection.Close ();
    52.         }
    53.         dbConnection = null;
    54.         Debug.Log ("Disconnected from db.");
    55.     }
    56.  
    57.  
    58.     /// <summary>
    59.     ///  Executes query given by sqlQuery
    60.     /// </summary>
    61.     /// <param name="sqlQuery">
    62.     /// query
    63.     /// A <see cref="System.String"/>
    64.     /// </param>
    65.     /// <returns>
    66.     /// null, if any error
    67.     /// result of query, otherwise
    68.     /// A <see cref="SqliteDataReader"/>
    69.     /// </returns>
    70.     public SqliteDataReader ExecuteQuery (string sqlQuery)
    71.     {
    72.         dbCommand = dbConnection.CreateCommand ();
    73.         dbCommand.CommandText = sqlQuery;
    74.        
    75.         reader = dbCommand.ExecuteReader ();
    76.        
    77.        
    78.         return reader;
    79.     }
    80.  
    81.     /// <summary>
    82.     ///  Selects everything from table
    83.     /// </summary>
    84.     /// <param name="tableName">
    85.     /// name of table
    86.     /// A <see cref="System.String"/>
    87.     /// </param>
    88.     /// <returns>
    89.     /// result of query
    90.     /// A <see cref="SqliteDataReader"/>
    91.     /// </returns>
    92.     public SqliteDataReader ReadFullTable (string tableName)
    93.     {
    94.         string query = "SELECT * FROM " + tableName;
    95.         return ExecuteQuery (query);
    96.     }
    97.  
    98.     /// <summary>
    99.     /// Inserts data into table
    100.     /// </summary>
    101.     /// <param name="tableName">
    102.     /// name of table to insert data
    103.     /// A <see cref="System.String"/>
    104.     /// </param>
    105.     /// <param name="values">
    106.     /// array of data in string representation
    107.     /// A <see cref="System.String[]"/>
    108.     /// </param>
    109.     /// <returns>
    110.     /// result of query
    111.     /// A <see cref="SqliteDataReader"/>
    112.     /// </returns>
    113.     public SqliteDataReader InsertInto (string tableName, string[] values)
    114.     {
    115.         string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
    116.         for (int i = 1; i < values.Length; ++i) {
    117.             query += ", " + values[i];
    118.         }
    119.         query += ")";
    120.         return ExecuteQuery (query);
    121.     }
    122.  
    123.     /// <summary>
    124.     /// Inserts data into specific columns of table
    125.     /// </summary>
    126.     /// <param name="tableName">
    127.     /// name of table
    128.     /// A <see cref="System.String"/>
    129.     /// </param>
    130.     /// <param name="cols">
    131.     /// name of columns
    132.     /// A <see cref="System.String[]"/>
    133.     /// </param>
    134.     /// <param name="values">
    135.     /// values
    136.     /// A <see cref="System.String[]"/>
    137.     /// </param>
    138.     /// <returns>
    139.     /// result of query
    140.     /// A <see cref="SqliteDataReader"/>
    141.     /// </returns>
    142.     public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)
    143.     {
    144.         if (cols.Length != values.Length) {
    145.             throw new SqliteException ("columns.Length != values.Length");
    146.         }
    147.         string query = "INSERT INTO " + tableName + "(" + cols[0];
    148.         for (int i = 1; i < cols.Length; ++i) {
    149.             query += ", " + cols[i];
    150.         }
    151.         query += ") VALUES (" + values[0];
    152.         for (int i = 1; i < values.Length; ++i) {
    153.             query += ", " + values[i];
    154.         }
    155.         query += ")";
    156.         return ExecuteQuery (query);
    157.     }
    158.  
    159.     /// <summary>
    160.     /// deletes any data from table
    161.     /// </summary>
    162.     /// <param name="tableName">
    163.     /// table name
    164.     /// A <see cref="System.String"/>
    165.     /// </param>
    166.     /// <returns>
    167.     /// result of query
    168.     /// A <see cref="SqliteDataReader"/>
    169.     /// </returns>
    170.     public SqliteDataReader DeleteContents (string tableName)
    171.     {
    172.         string query = "DELETE FROM " + tableName;
    173.         return ExecuteQuery (query);
    174.     }
    175.  
    176.     /// <summary>
    177.     /// Creates table with specified columns
    178.     /// </summary>
    179.     /// <param name="name">
    180.     /// table name to be created
    181.     /// A <see cref="System.String"/>
    182.     /// </param>
    183.     /// <param name="col">
    184.     /// array, containing names of columns
    185.     /// A <see cref="System.String[]"/>
    186.     /// </param>
    187.     /// <param name="colType">
    188.     /// array, containing types of columns
    189.     /// A <see cref="System.String[]"/>
    190.     /// </param>
    191.     /// <returns>
    192.     /// result of query
    193.     /// A <see cref="SqliteDataReader"/>
    194.     /// </returns>
    195.     public SqliteDataReader CreateTable (string name, string[] col, string[] colType)
    196.     {
    197.         if (col.Length != colType.Length) {
    198.             throw new SqliteException ("columns.Length != colType.Length");
    199.         }
    200.         string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
    201.         for (int i = 1; i < col.Length; ++i) {
    202.             query += ", " + col[i] + " " + colType[i];
    203.         }
    204.         query += ")";
    205.         return ExecuteQuery (query);
    206.     }
    207.  
    208.     /// <summary>
    209.     /// Selects from table with specified parameters.
    210.     /// Ex: SelectWhere("puppies", new string[] = {"breed"}, new string[] = {"earType"}, new string[] = {"="}, new string[] = {"floppy"});
    211.     /// the same as command: SELECT breed FROM puppies WHERE earType = floppy
    212.     /// </summary>
    213.     /// <param name="tableName">
    214.     /// name of table to select
    215.     /// A <see cref="System.String"/>
    216.     /// </param>
    217.     /// <param name="items">
    218.     /// item names
    219.     /// A <see cref="System.String[]"/>
    220.     /// </param>
    221.     /// <param name="col">
    222.     /// array, containing columns of parameters
    223.     /// A <see cref="System.String[]"/>
    224.     /// </param>
    225.     /// <param name="operation">
    226.     /// A <see cref="System.String[]"/>
    227.     /// </param>
    228.     /// <param name="values">
    229.     /// A <see cref="System.String[]"/>
    230.     /// </param>
    231.     /// <returns>
    232.     /// result of query
    233.     /// A <see cref="SqliteDataReader"/>
    234.     /// </returns>
    235.     public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)
    236.     {
    237.         if (col.Length != operation.Length || operation.Length != values.Length) {
    238.             throw new SqliteException ("col.Length != operation.Length != values.Length");
    239.         }
    240.         string query = "SELECT " + items[0];
    241.         for (int i = 1; i < items.Length; ++i) {
    242.             query += ", " + items[i];
    243.         }
    244.         query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
    245.         for (int i = 1; i < col.Length; ++i) {
    246.             query += " AND " + col[i] + operation[i] + "'" + values[0] + "' ";
    247.         }
    248.        
    249.         return ExecuteQuery (query);
    250.        
    251.     }
    252.    
    253.    
    254.    
    255. }

    If you find any bugs please report to this thread.


  18. Posts
    3
    how to do the UPDATE? is it similar with INSERT syntaxs? thanks!


  19. Posts
    46
    Sorry for bumping this old topic, but whenever I try to use the SingleSelectWhere it tells me the syntax is wrong. When I enter a plain string query without a WHERE clause it works, same with WHERE field=integer but as soon as i try WHERE field=STRING / 'STRING' it does not work... does anyone know how to get this working?

    Thanks in advance.


  20. Posts
    11
    If all this stuff is making you feel uneasy, take a close look at this asset: http://u3d.as/content/mono-sapiens-ltda/mono-sqlite/2Qw

    Its goal is to unify SQLite solution for Unity3D