导读: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 da
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:
import System.
Data;
// we import our data class
import Mono.
Data.
SqliteClient;
// we import our sqlite client
class dbAccess
{
// variables for basic query access
private
var connection :
String;
var dbcon : IDbConnection;
var dbcmd : IDbCommand;
var reader : IDataReader;
function OpenDB
(p :
String)
connection =
"URI=file:" + p;
// we set the connection to our database
dbcon =
new SqliteConnection
(connection
);
dbcon.
Open(}
function BasicQuery
(q :
String,r :
boolean{// run a baic Sqlite query
function InsertInto
// basic Insert with just values
" VALUES (" + values
function SingleSelectWhere
// Selects a single Item
"SELECT " + itemToSelect +
" FROM " + tableName +
" WHERE " + wCol + wPar + wValue;
var readArray =
new
while
(reader.
Read
readArray.
Push(reader.
GetString
// Fill array with all matches
return readArray;
// return matches
function CloseDB
reader.
Close// clean everything up
reader =
null;
dbcmd.
Dispose
dbcmd =
dbcon.
dbcon =
}
An Example of Creating a Table You can create two arrays,one being the column headers,and another being the data types.
Code:
var db : dbAccess;
function
Start
db =
new dbAccess
db.
OpenDB("myDB.sqdb"var tableName =
"myTable";
var columnNames =
"firstName","lastName"var columnValues =
"text",21)">"text"
CreateTable(tableName,columnNames,columnValues
CloseDB}
An Example of Easy Insert This example is an easy way to add a single record
Code:
// IMPORTANT remember to add single ' to any strings,do not add them to numbers!
var values =
"'Bob'",21)">"'Sagat'"
InsertInto}
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:
// table name,I want to return everyone whose first name is Bob when their last name is = to Sagat,this returs an array
var resultArray = db.
SingleSelectWhere"lastName",21)">"=",0)">// Remember the '' on String values
print
(resultArray
]// of course you can loop through them all if you wish