URL: bbs.9ria. comforum. php? Modviewthreadtid168629fromuid308561 over the past few days, I also studied how Unity3D can be directly connected to the Sqlite database. Don't talk nonsense. Let's talk about it directly. The original Article is from: wiki. unity3d. comindex. phpSqlite. You can learn it. 1,
URL: http://bbs.9ria.com/forum.php? Mod = viewthreadtid = 168629 fromuid = 308561 over the past few days, I also studied how Unity3D can be directly connected to the Sqlite database. Don't talk nonsense. Let's talk about it directly. The original Article from: http://wiki.unity3d.com/index.php/Sqlite, you can learn. 1,
URL: http://bbs.9ria.com/forum.php? Mod = viewthread & tid = 168629 & fromuid = 308561
In the past few days, I have also studied how Unity3D can be directly connected to the Sqlite database. Don't talk nonsense. Let's talk about it directly. The original Article is from: http://wiki.unity3d.com/index.php/sqlite. you can learn it now.
1. Environment Introduction:
Windows 7, Unity3D, SQLite Expert Personal 3
2. Development language:
JavaScript
3. required dll files:
Mono. Data. Sqlite. dll and sqlite3.dll. I will package all the files for discussion later. Let's take a look at where these dll files should be put and see the following:
, Must be in this directory, please be consistent with me.
4. If you need to release the compiled program successfully, you need to modify the code. For details, see the following:
I have marked the change in red. Note that this should be changed to. NET2.0 for release. The default value is not. NET2.0. Please pay attention to this !!!
5. Let's take a look at the code below. Let's first look at how to create the database code. This Code does not need to be mounted to any object. You just need to use it as a tool. As follows:
/* Javascript class for accessing SQLite objects.
To use it, you need to make sure you COPY Mono. Data. SQLiteClient. dll from wherever it lives in your Unity directory
To your project's Assets folder
Originally created by dklompmaker in 2009
Http://forum.unity3d.com/threads... sier-Database-Stuff
Modified 2011 by Alan Chatham */
// # Pragma strict
/* Code Description
* This code is written to run the unity3d and Sqlite databases in a Windows environment. The basic function is that unity3d can communicate with databases. For example
After the data in the database is changed, the data in unity3d will be refreshed and changed. This is just a basic core technology, in order to be applied to large-scale unity3d
In a project, you can store the properties of a project in a scenario. It can be easily used when you need to change the attributes of an object, such as adding or decreasing objects.
To implement this code. First, you need some dll files, Mono. Data. SQLiteClient. dll and sqlite3.dll, which can be found in the unity3d installation directory.
In addition, you need to put these two files under the path of your project: \ Assets \ Plugins \. This folder must be created without the Plugins folder, then write the two dll files in the folder.
Of course, if you want to publish an executable file on a PC, you still need to modify it. In Play Setting-> Other Setting in unity3d, change the level of Api Compatibility
. NET 2.0; after these operations are completed, if your code is well written, you can succeed.
Now let's explain the code in detail.
- *
- */
- Import System. Data; // we import our data class. we first import our Dataset
- Import Mono. Data. Sqlite; // we import sqlite. we import the sqlite dataset, that is, the dll file in the Plugins folder.
- Class dbAccess {
- // Variables for basic query access
- Private var connection: String; // database connection String, used to establish a connection with a specific data source
- Private var dbcon: IDbConnection; // connection object of IDbConnection, which is actually a Class Object
- Private var dbcmd: IDbCommand; // The IDbCommand class object, which is used to perform database operation commands: Note: How can I execute commands on the database on the Internet:
- // Create an IDbConnection connection object, assign a database command to a string, and use this string and the connection object
- // You can create (new) An IDbCommand object, and then run this command using the provided method.
- Private var reader: IDataReader; // reader is used to read one or more result streams.
- Function OpenDB (p: String ){
- Connection = "URI = file:" + p; // we set the connection to our database
- Dbcon = new SqliteConnection (connection );
- Dbcon. Open (); // Open the database connection operation
- }
- Function BasicQuery (q: String, r: boolean) {// run a baic Sqlite query
- Dbcmd = dbcon. CreateCommand (); // create empty command
- Dbcmd. CommandText = q; // fill the command
- Reader = dbcmd. ExecuteReader (); // execute command which returns a reader returns the IDataReader object and creates the IDataReader object
- If (r) {// if we want to return the reader
- Return reader; // return the reader returns the read object, that is, what is read
- }
- }
- // This returns a 2 dimen1_arraylist with all
- // Data from the table requested
- Function ReadFullTable (tableName: String ){
- Var query: String;
- Query = "SELECT * FROM" + tableName;
- Dbcmd = dbcon. CreateCommand ();
- Dbcmd. CommandText = query;
- Reader = dbcmd. ExecuteReader ();
- Var readArray = new ArrayList ();
- While (reader. Read ()){
- Var lineArray = new ArrayList ();
- For (var I = 0; I <reader. FieldCount; I ++)
- LineArray. Add (reader. GetValue (I); // This reads the entries in a row
- ReadArray. Add (lineArray); // This makes an array of all the rows
- }
- Return readArray; // return matches
- }
- // This function deletes all the data in the given table. Forever. watch out! Use sparingly, if at all
- Function DeleteTableContents (tableName: String ){
- Var query: String;
- Query = "delete from" + tableName;
- Dbcmd = dbcon. CreateCommand ();
- Dbcmd. CommandText = query;
- Reader = dbcmd. ExecuteReader ();
- }
- Function CreateTable (name: String, col: Array, colType: Array) {// Create a table, name, column array, column type array
- Var query: String;
- Query = "create table" + name + "(" + col [0] + "" + colType [0];
- For (var I = 1; I
- Query + = "," + col + "" + colType;
- }
- Query + = ")";
- Dbcmd = dbcon. CreateCommand (); // create empty command
- Dbcmd. CommandText = query; // fill the command
- Reader = dbcmd. ExecuteReader (); // execute command which returns a reader
- }
- Function InsertIntoSingle (tableName: String, colName: String, value: String) {// single insert
- Var query: String;
- Query = "insert into" + tableName + "(" + colName + ")" + "VALUES (" + value + ")";
- Dbcmd = dbcon. CreateCommand (); // create empty command
- Dbcmd. CommandText = query; // fill the command
- Reader = dbcmd. ExecuteReader (); // execute command which returns a reader
- }
- Function insertintospecpacific (tableName: String, col: Array, values: Array) {// Specific insert with col and values
- Var query: String;
- Query = "insert into" + tableName + "(" + col [0];
- For (var I = 1; I
- Query + = "," + col;
- }
- Query + = ") VALUES (" + values [0];
- For (I = 1; I
- Query + = "," + values;
- }
- Query + = ")";
- Dbcmd = dbcon. CreateCommand ();
- Dbcmd. CommandText = query;
- Reader = dbcmd. ExecuteReader ();
- }
- Function InsertInto (tableName: String, values: Array) {// basic Insert with just values
- Var query: String;
- Query = "insert into" + tableName + "VALUES (" + values [0];
- For (var I = 1; I
- Query + = "," + values;
- }
- Query + = ")";
- Dbcmd = dbcon. CreateCommand ();
- Dbcmd. CommandText = query;
- Reader = dbcmd. ExecuteReader ();
- }
- // This function reads a single column
- // WCol is the WHERE column, wPar is the operator you want to use to compare,
- // And wValue is the value you want to compare against.
- // Ex.-SingleSelectWhere ("puppies", "breed", "earType", "=", "floppy ")
- // Returns an array of matches from the command: SELECT breed FROM puppies WHERE earType = floppy;
- Function SingleSelectWhere (tableName: String, itemToSelect: String, wCol: String, wPar: String, wValue: String) {// Selects a single Item
- Var query: String;
- Query = "SELECT" + itemToSelect + "FROM" + tableName + "WHERE" + wCol + wPar + wValue;
- Dbcmd = dbcon. CreateCommand ();
- Dbcmd. CommandText = query;
- Reader = dbcmd. ExecuteReader ();
- Var readArray = new Array ();
- While (reader. Read ()){
- ReadArray. Push (reader. GetString (0); // Fill array with all matches
- }
- Return readArray; // return matches
- }
- Function CloseDB (){
- Reader. Close (); // clean everything up
- Reader = null;
- Dbcmd. Dispose ();
- Dbcmd = null;
- Dbcon. Close ();
- Dbcon = null;
- }
- }
The basic addition, deletion, modification, and query of the above Code are all available. If you take a closer look and add my comments, this code is not difficult. It may be a bit unacceptable for beginners. To be honest, I am also a beginner, if there is no original text, I absolutely cannot write this...
7. Now let's take a look at how to use the database code in Unity3D:
- // # Pragma strict
- /* Script for testing out SQLite in Javascript
- 2011-Alan Chatham
- Released into the public domain
- This script is a GUI script-attach it to your main camera.
- It creates/opens a SQLite database, and with the GUI you can read and write to it.
- */
- // This is the file path of the database file we want to use
- // Right now, it'll load TestDB. sqdb in the project's root folder.
- // If one doesn't exist, it will be automatically created.
- Public var DatabaseName: String = "TestDB. sqdb ";
- // This is the name of the table we want to use
- Public var TableName: String = "TestTable ";
- Var db: dbAccess;
- Function Start (){
- // Give ourselves a dbAccess object to work with, and open it
- Db = new dbAccess ();
- Db. OpenDB (DatabaseName );
- // Let's make sure we 've ve got a table to work with as well!
- Var tableName = TableName;
- Var columnNames = new Array ("firstName", "lastName ");
- Var columnValues = new Array ("text", "text ");
- Try {db. CreateTable (tableName, columnNames, columnValues );
- }
- Catch (e) {// Do nothing-our table was already created
- //-We don't care about the error, we just don't want to see it
- }
- }
- // These variables just hold info to display in our GUI
- Var firstName: String = "First Name ";
- Var lastName: String = "Last Name ";
- Var DatabaseEntryStringWidth = 100;
- Var scrollPosition: Vector2;
- Var databaseData: ArrayList = new ArrayList ();
- // This GUI provides us with a way to enter data into our database
- // As well as a way to view it
- Function OnGUI (){
- GUI. Box (Rect (25, 25, Screen. width-50, Screen. height-50), "Data ");
- GUILayout. BeginArea (Rect (50, 50, Screen. width-100, Screen. height-100 ));
- // This first block allows us to enter new entries into our table
- GUILayout. BeginHorizontal ();
- FirstName = GUILayout. TextField (firstName, GUILayout. Width (DatabaseEntryStringWidth ));
- LastName = GUILayout. TextField (lastName, GUILayout. Width (DatabaseEntryStringWidth ));
- // LastName = GUILayout. TextField ();
- GUILayout. EndHorizontal ();
- If (GUILayout. Button ("Add to database ")){
- // Insert the data
- InsertRow (firstName, lastName );
- // And update the readout of the database
- DatabaseData = ReadFullTable ();
- }
- // This second block gives us a button that will display/refresh the contents of our database
- GUILayout. BeginHorizontal ();
- If (GUILayout. Button ("Read Database "))
- DatabaseData = ReadFullTable ();
- If (GUILayout. Button ("Clear "))
- DatabaseData. Clear ();
- GUILayout. EndHorizontal ();
- GUILayout. Label ("Database Contents ");
- ScrollPosition = GUILayout. BeginScrollView (scrollPosition, GUILayout. Height (100 ));
- For (var line: ArrayList in databaseData ){
- GUILayout. BeginHorizontal ();
- For (var s in line ){
- GUILayout. Label (s. ToString (), GUILayout. Width (DatabaseEntryStringWidth ));
- }
- GUILayout. EndHorizontal ();
- }
- GUILayout. EndScrollView ();
- If (GUILayout. Button ("Delete All Data") {unity3dand sqlitedata warehouse are directly connected to .rar (168.27 KB, download times: 239)
- Unity3dand sqlitedata warehouse direct connection .rar (446.06 KB, downloads: 584)
- DeleteTableContents ();
- DatabaseData = ReadFullTable ();
- }
- GUILayout. EndArea ();
- }
- // Wrapper function for inserting our specific entries into our specific database and table for this file
- Function InsertRow (firstName, lastName ){
- Var values = new Array ("'" + firstName + "'"), ("'" + lastName + "'"));
- Db. InsertInto (TableName, values );
- }
- // Wrapper function, so we only mess with our table.
- Function ReadFullTable (){
- Return db. ReadFullTable (TableName );
- }
- // Another wrapper function...
- Function DeleteTableContents (){
- Db. DeleteTableContents (TableName );
- }
This piece of code is intended for you to stick on your main camera. In fact, I am not very familiar with the database, and I do not understand it in many places, I hope that some of you can annotate this code in detail so that we can fully absorb this cainiao-level code...
9. Let's take a look at our running results below:
This is the result of running in Unity3D. What will happen to the data operation?
We can see that our data operations can be successful. After testing, other buttons can also have the corresponding effect. Then we can see whether the desired database file is generated:
Let's take a look:
No, we generated the database file we wanted. Let's take a look at the data in this file:
- We have succeeded. After testing, when we operate on the data in the database, the data in our Unity3D will change accordingly. Therefore, this time we have succeeded. Here, we would like to thank the original article for its support. Hope that the passing experts will not spray it...