2017년 12월 26일 화요일

Unity - Local DB - C# - Sqlite




The Class
Code (csharp):
  1. import          System.Data;  // we import our  data class
  2. import          Mono.Data.SqliteClient// we import our sqlite client
  3. class dbAccess {
  4.     // variables for basic query access
  5.     private var connection : String;
  6.     private var dbcon : IDbConnection;
  7.     private var dbcmd : IDbCommand;
  8.     private var reader : IDataReader;
  9.    
  10.     function OpenDB(: String){
  11.     connection = "URI=file:" + p; // we set the connection to our database
  12.     dbcon = new SqliteConnection(connection);
  13.     dbcon.Open();
  14.     }
  15.    
  16.     function BasicQuery(: String, r : boolean){ // run a baic Sqlite query
  17.         dbcmd = dbcon.CreateCommand()// create empty command
  18.         dbcmd.CommandText = q; // fill the command
  19.         reader = dbcmd.ExecuteReader()// execute command which returns a reader
  20.         if(r){ // if we want to return the reader
  21.         return reader; // return the reader
  22.         }
  23.     }
  24.    
  25.     function CreateTable(name : String, col : Array, colType : Array){ // Create a table, name, column array, column type array
  26.         var query : String;
  27.         query  = "CREATE TABLE " + name + "(" + col[0] + " " + colType[0];
  28.         for(var i=1; i<col.length; i++){
  29.             query += ", " + col[i] + " " + colType[i];
  30.         }
  31.         query += ")";
  32.         dbcmd = dbcon.CreateCommand()// create empty command
  33.         dbcmd.CommandText = query; // fill the command
  34.         reader = dbcmd.ExecuteReader()// execute command which returns a reader
  35.    
  36.     }
  37.    
  38.     function InsertIntoSingle(tableName : String, colName : Stringvalue : String){ // single insert
  39.         var query : String;
  40.         query = "INSERT INTO " + tableName + "(" + colName + ") " + "VALUES (" + value + ")";
  41.         dbcmd = dbcon.CreateCommand()// create empty command
  42.         dbcmd.CommandText = query; // fill the command
  43.         reader = dbcmd.ExecuteReader()// execute command which returns a reader
  44.     }
  45.    
  46.     function InsertIntoSpecific(tableName : String, col : Array, values : Array){ // Specific insert with col and values
  47.         var query : String;
  48.         query = "INSERT INTO " + tableName + "(" + col[0];
  49.         for(var i=1; i<col.length; i++){
  50.             query += ", " + col[i];
  51.         }
  52.         query += ") VALUES (" + values[0];
  53.         for(i=1; i<values.length; i++){
  54.             query += ", " + values[i];
  55.         }
  56.         query += ")";
  57.         dbcmd = dbcon.CreateCommand();
  58.         dbcmd.CommandText = query;
  59.         reader = dbcmd.ExecuteReader();
  60.     }
  61.    
  62.     function InsertInto(tableName : String, values : Array){ // basic Insert with just values
  63.         var query : String;
  64.         query = "INSERT INTO " + tableName + " VALUES (" + values[0];
  65.         for(var i=1; i<values.length; i++){
  66.             query += ", " + values[i];
  67.         }
  68.         query += ")";
  69.         dbcmd = dbcon.CreateCommand();
  70.         dbcmd.CommandText = query;
  71.         reader = dbcmd.ExecuteReader();
  72.     }
  73.    
  74.     function SingleSelectWhere(tableName : String, itemToSelect : String, wCol : String, wPar : String, wValue : String){ // Selects a single Item
  75.         var query : String;
  76.         query = "SELECT " + itemToSelect + " FROM " + tableName + " WHERE " + wCol + wPar + wValue;
  77.         dbcmd = dbcon.CreateCommand();
  78.         dbcmd.CommandText = query;
  79.         reader = dbcmd.ExecuteReader();
  80.         var readArray = new Array();
  81.         while(reader.Read()){
  82.             readArray.Push(reader.GetString(0))// Fill array with all matches
  83.         }
  84.         return readArray; // return matches
  85.     }
  86.    
  87.     function CloseDB(){
  88.         reader.Close()// clean everything up
  89.         reader = null;
  90.         dbcmd.Dispose();
  91.         dbcmd = null;
  92.         dbcon.Close();
  93.         dbcon = null;
  94.     }
  95.    
  96. }
An Example of Creating a Table
You can create two arrays, one being the column headers, and another being the data types.
Code (csharp):
  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 (csharp):
  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 (csharp):
  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. }
de (csharp):
  1. using UnityEngine;
  2. using System;
  3. using Mono.Data.Sqlite;
  4. public class DbAccess
  5. {
  6.     private SqliteConnection dbConnection;
  7.     private SqliteCommand dbCommand;
  8.     private SqliteDataReader reader;
  9.     /// <summary>
  10.     ///  string to connect. The simpliest one looks like "URI=file:filename.db"
  11.     /// </summary>
  12.     /// <param name="connectionString">
  13.     /// A <see cref="System.String"/>
  14.     /// </param>
  15.     public DbAccess (string connectionString)
  16.     {
  17.         OpenDB (connectionString);
  18.     }
  19.     /// <summary>
  20.     ///  The same as <see cref="DbAccess#Dbaccess" / >
  21.     /// </summary>
  22.     /// <param name="connectionString">
  23.     /// A <see cref="System.String"/>
  24.     /// </param>
  25.     public void OpenDB (string connectionString)
  26.     {
  27.         dbConnection = new SqliteConnection (connectionString);
  28.         dbConnection.Open ();
  29.         Debug.Log ("Connected to db");
  30.     }
  31.     /// <summary>
  32.     /// Closes connection to db
  33.     /// </summary>
  34.     public void CloseSqlConnection ()
  35.     {
  36.         if (dbCommand != null) {
  37.             dbCommand.Dispose ();
  38.         }
  39.         dbCommand = null;
  40.         if (reader != null) {
  41.             reader.Dispose ();
  42.         }
  43.         reader = null;
  44.         if (dbConnection != null) {
  45.             dbConnection.Close ();
  46.         }
  47.         dbConnection = null;
  48.         Debug.Log ("Disconnected from db.");
  49.     }
  50.     /// <summary>
  51.     ///  Executes query given by sqlQuery
  52.     /// </summary>
  53.     /// <param name="sqlQuery">
  54.     /// query
  55.     /// A <see cref="System.String"/>
  56.     /// </param>
  57.     /// <returns>
  58.     /// null, if any error
  59.     /// result of query, otherwise
  60.     /// A <see cref="SqliteDataReader"/>
  61.     /// </returns>
  62.     public SqliteDataReader ExecuteQuery (string sqlQuery)
  63.     {
  64.         dbCommand = dbConnection.CreateCommand ();
  65.         dbCommand.CommandText = sqlQuery;
  66.        
  67.         reader = dbCommand.ExecuteReader ();
  68.        
  69.        
  70.         return reader;
  71.     }
  72.     /// <summary>
  73.     ///  Selects everything from table
  74.     /// </summary>
  75.     /// <param name="tableName">
  76.     /// name of table
  77.     /// A <see cref="System.String"/>
  78.     /// </param>
  79.     /// <returns>
  80.     /// result of query
  81.     /// A <see cref="SqliteDataReader"/>
  82.     /// </returns>
  83.     public SqliteDataReader ReadFullTable (string tableName)
  84.     {
  85.         string query = "SELECT * FROM " + tableName;
  86.         return ExecuteQuery (query);
  87.     }
  88.     /// <summary>
  89.     /// Inserts data into table
  90.     /// </summary>
  91.     /// <param name="tableName">
  92.     /// name of table to insert data
  93.     /// A <see cref="System.String"/>
  94.     /// </param>
  95.     /// <param name="values">
  96.     /// array of data in string representation
  97.     /// A <see cref="System.String[]"/>
  98.     /// </param>
  99.     /// <returns>
  100.     /// result of query
  101.     /// A <see cref="SqliteDataReader"/>
  102.     /// </returns>
  103.     public SqliteDataReader InsertInto (string tableName, string[] values)
  104.     {
  105.         string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
  106.         for (int i = 1; i < values.Length++i) {
  107.             query += ", " + values[i];
  108.         }
  109.         query += ")";
  110.         return ExecuteQuery (query);
  111.     }
  112.     /// <summary>
  113.     /// Inserts data into specific columns of table
  114.     /// </summary>
  115.     /// <param name="tableName">
  116.     /// name of table
  117.     /// A <see cref="System.String"/>
  118.     /// </param>
  119.     /// <param name="cols">
  120.     /// name of columns
  121.     /// A <see cref="System.String[]"/>
  122.     /// </param>
  123.     /// <param name="values">
  124.     /// values
  125.     /// A <see cref="System.String[]"/>
  126.     /// </param>
  127.     /// <returns>
  128.     /// result of query
  129.     /// A <see cref="SqliteDataReader"/>
  130.     /// </returns>
  131.     public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)
  132.     {
  133.         if (cols.Length != values.Length) {
  134.             throw new SqliteException ("columns.Length != values.Length");
  135.         }
  136.         string query = "INSERT INTO " + tableName + "(" + cols[0];
  137.         for (int i = 1; i < cols.Length++i) {
  138.             query += ", " + cols[i];
  139.         }
  140.         query += ") VALUES (" + values[0];
  141.         for (int i = 1; i < values.Length++i) {
  142.             query += ", " + values[i];
  143.         }
  144.         query += ")";
  145.         return ExecuteQuery (query);
  146.     }
  147.     /// <summary>
  148.     /// deletes any data from table
  149.     /// </summary>
  150.     /// <param name="tableName">
  151.     /// table name
  152.     /// A <see cref="System.String"/>
  153.     /// </param>
  154.     /// <returns>
  155.     /// result of query
  156.     /// A <see cref="SqliteDataReader"/>
  157.     /// </returns>
  158.     public SqliteDataReader DeleteContents (string tableName)
  159.     {
  160.         string query = "DELETE FROM " + tableName;
  161.         return ExecuteQuery (query);
  162.     }
  163.     /// <summary>
  164.     /// Creates table with specified columns
  165.     /// </summary>
  166.     /// <param name="name">
  167.     /// table name to be created
  168.     /// A <see cref="System.String"/>
  169.     /// </param>
  170.     /// <param name="col">
  171.     /// array, containing names of columns
  172.     /// A <see cref="System.String[]"/>
  173.     /// </param>
  174.     /// <param name="colType">
  175.     /// array, containing types of columns
  176.     /// A <see cref="System.String[]"/>
  177.     /// </param>
  178.     /// <returns>
  179.     /// result of query
  180.     /// A <see cref="SqliteDataReader"/>
  181.     /// </returns>
  182.     public SqliteDataReader CreateTable (string namestring[] col, string[] colType)
  183.     {
  184.         if (col.Length != colType.Length) {
  185.             throw new SqliteException ("columns.Length != colType.Length");
  186.         }
  187.         string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
  188.         for (int i = 1; i < col.Length++i) {
  189.             query += ", " + col[i] + " " + colType[i];
  190.         }
  191.         query += ")";
  192.         return ExecuteQuery (query);
  193.     }
  194.     /// <summary>
  195.     /// Selects from table with specified parameters.
  196.     /// Ex: SelectWhere("puppies", new string[] = {"breed"}, new string[] = {"earType"}, new string[] = {"="}, new string[] = {"floppy"});
  197.     /// the same as command: SELECT breed FROM puppies WHERE earType = floppy
  198.     /// </summary>
  199.     /// <param name="tableName">
  200.     /// name of table to select
  201.     /// A <see cref="System.String"/>
  202.     /// </param>
  203.     /// <param name="items">
  204.     /// item names
  205.     /// A <see cref="System.String[]"/>
  206.     /// </param>
  207.     /// <param name="col">
  208.     /// array, containing columns of parameters
  209.     /// A <see cref="System.String[]"/>
  210.     /// </param>
  211.     /// <param name="operation">
  212.     /// A <see cref="System.String[]"/>
  213.     /// </param>
  214.     /// <param name="values">
  215.     /// A <see cref="System.String[]"/>
  216.     /// </param>
  217.     /// <returns>
  218.     /// result of query
  219.     /// A <see cref="SqliteDataReader"/>
  220.     /// </returns>
  221.     public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)
  222.     {
  223.         if (col.Length != operation.Length || operation.Length != values.Length) {
  224.             throw new SqliteException ("col.Length != operation.Length != values.Length");
  225.         }
  226.         string query = "SELECT " + items[0];
  227.         for (int i = 1; i < items.Length++i) {
  228.             query += ", " + items[i];
  229.         }
  230.         query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
  231.         for (int i = 1; i < col.Length++i) {
  232.             query += " AND " + col[i] + operation[i] + "'" + values[0] + "' ";
  233.         }
  234.        
  235.         return ExecuteQuery (query);
  236.        
  237.     }
  238.    
  239.    
  240.    
  241. }


de (JavaScript):
  1. #pragma strict
  2. /*  Script for testing out SQLite in Javascript
  3.           2011 - Alan Chatham
  4.           Released into the public domain
  5.         This script is a GUI script - attach it to your main camera.
  6.         It creates/opens a SQLite database, and with the GUI you can read and write to it.
  7.                                         */
  8. // This is the file path of the database file we want to use
  9. // Right now, it'll load TestDB.sqdb in the project's root folder.
  10. // If one doesn't exist, it will be automatically created.
  11. public var DatabaseName : String = "TestDB.sqdb";
  12. // This is the name of the table we want to use
  13. public var TableName : String = "TestTable";
  14. var db : dbAccess;
  15. function Start() {
  16.     // Give ourselves a dbAccess object to work with, and open it
  17.     db = new dbAccess();
  18.     db.OpenDB(DatabaseName);
  19.     // Let's make sure we've got a table to work with as well!
  20.     var tableName = TableName;
  21.     //var columnNames = new Array("firstName","lastName");
  22.     var columnNames = new Array("firstName","lastName", "age"); // o negocio e mais embaixo
  23.     //var columnValues = new Array("text","text");
  24.     var columnValues = new Array("text","text", "text");
  25.     try {
  26.         db.CreateTable(tableName,columnNames,columnValues);
  27.     }
  28.     catch(e) {// Do nothing - our table was already created
  29.         //- we don't care about the error, we just don't want to see it
  30.     }
  31. }
  32. // These variables just hold info to display in our GUI
  33. var firstName : String = "First Name";
  34. var lastName : String = "Last Name";
  35. var age : String = "Age";
  36. var DatabaseEntryStringWidth = 100;
  37. var scrollPosition : Vector2;
  38. var databaseData : ArrayList = new ArrayList();
  39. // This GUI provides us with a way to enter data into our database
  40. //  as well as a way to view it
  41. function OnGUI() {
  42.     GUI.Box(Rect (25,25,Screen.width - 50, Screen.height - 50),"");
  43.     GUILayout.BeginArea(Rect(50, 50, Screen.width - 100, Screen.height - 100));
  44.     // This first block allows us to enter new entries into our table
  45.         GUILayout.BeginHorizontal();
  46.             firstName = GUILayout.TextField(firstName, GUILayout.Width (DatabaseEntryStringWidth));
  47.             lastName = GUILayout.TextField(lastName, GUILayout.Width (DatabaseEntryStringWidth));
  48.             age = GUILayout.TextField(age, GUILayout.Width (DatabaseEntryStringWidth));
  49.         GUILayout.EndHorizontal();
  50.         if (GUILayout.Button("Add to database")) {
  51.             // Insert the data
  52.            //InsertRow(firstName,lastName);
  53.            InsertRow(firstName,lastName,age);
  54.             // And update the readout of the database
  55.             databaseData = ReadFullTable();
  56.         }
  57.         // This second block gives us a button that will display/refresh the contents of our database
  58.         GUILayout.BeginHorizontal();
  59.             if (GUILayout.Button ("Read Database"))
  60.                 databaseData = ReadFullTable();
  61.             if (GUILayout.Button("Clear"))
  62.                 databaseData.Clear();
  63.         GUILayout.EndHorizontal();
  64.         GUILayout.Label("Database Contents");
  65.         scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(100));
  66.             for (var line : ArrayList in databaseData) {
  67.                 GUILayout.BeginHorizontal();
  68.                 for (var s in line) {
  69.                     GUILayout.Label(s.ToString(), GUILayout.Width(DatabaseEntryStringWidth));
  70.                 }
  71.                 GUILayout.EndHorizontal();
  72.             }
  73.         GUILayout.EndScrollView();
  74.         if (GUILayout.Button("Delete All Data")) {
  75.             DeleteTableContents();
  76.             databaseData = ReadFullTable();
  77.         }
  78.     GUILayout.EndArea();
  79. }
  80. // Wrapper function for inserting our specific entries into our specific database and table for this file
  81. //function InsertRow(firstName:String, lastName:String) {
  82. function InsertRow(firstName:String, lastName:String, age:String) { //
  83.   //var values = new Array(("'"+firstName+"'"),("'"+lastName+"'"));
  84.     var values = new Array(("'"+firstName+"'"),("'"+lastName+"'"),("'"+age+"'"));
  85.     db.InsertInto(TableName, values);
  86. }
  87. // Wrapper function, so we only mess with our table.
  88. function ReadFullTable() {
  89.     return db.ReadFullTable(TableName);
  90. }
  91. // Another wrapper function...
  92. function DeleteTableContents() {
  93.     db.DeleteTableContents(TableName);
  94. }



댓글 없음:

댓글 쓰기

javascript - SQL 예약어 제거

  <script language="javascript"> //특수문자, 특정문자열(sql예약어) 제거 function checkSearchedWord(obj){ obj.value = obj.value+&quo...