Okay, I plan to make an open world RPG game where I will use the database to store inventory, quest, and everything.
I manage to make the basic code working.
It can connect and read the desired value.
Here are the code;
using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System.Data;
using System;
public class DBAccess : MonoBehaviour {
// Use this for initialization
void Start () {
string connectionString = "URI=file:" +Application.dataPath + "/GameMaster"; //Path to database.
IDbConnection dbcon;
dbcon = (IDbConnection) new SqliteConnection(connectionString);
dbcon.Open(); //Open connection to the database.
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "SELECT firstname, lastname " + "FROM addressbook";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
while(reader.Read()) {
string FirstName = reader.GetString (0);
string LastName = reader.GetString (1);
Console.WriteLine("Name: " +
FirstName + " " + LastName);
Debug.Log (FirstName + LastName);
}
// clean up
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
dbcon = null;
}
// Update is called once per frame
void Update () {
}
void OnGUI () {
string connectionString = "URI=file:" +Application.dataPath + "/GameMaster"; //Path to database.
IDbConnection dbcon;
dbcon = (IDbConnection) new SqliteConnection(connectionString);
dbcon.Open(); //Open connection to the database.
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "SELECT firstname FROM addressbook WHERE rowid=1";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
while(reader.Read()) {
string FirstName = reader.GetString (0);
//string LastName = reader.GetString (1);
//Console.WriteLine("Name: " +
//FirstName + " " + LastName);
//Debug.Log (FirstName + LastName);
GUI.Box (new Rect (Screen.width - 270, Screen.height - 55, 260, 30), "Copyright "+FirstName+" 2014");
}
// clean up
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
dbcon = null;
}
}
Here are the screenshots of what the code suppose to do.
I read that the database connection must be close as soon as possible, so do I need to repeat the whole code of opening, and reading the value whenever I need them?
Can someone show me how to just run an sql queries on the spot whenever I need the value just like when we use a variable?