Unity의 데이터베이스 구축 및 읽기/쓰기 상세 정보

두 가지 클래스, DbAccess 및 TestDB
TestDB 클래스 테스트, 데이터베이스 만들기, 데이터 테이블 만들기, 데이터 삽입, 데이터 업데이트, 데이터 삭제, 데이터 조회
using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System.IO;

public class TestDB : MonoBehaviour {

	DbAccess db;	//   
	string appDBPath;	//     

	string name;
	int age;
	float exp;

	//     
	void CreateDataBase()
	{
#if UNITY_EDITOR
		appDBPath = Application.dataPath + "/Test.db";
#elif UNITY_STANDALONE_WIN
		appDBPath = Application.dataPath + "/Test.db";
#elif UNITY_ANDROID
		appDBPath = Application.persistentDataPath + "/Test.db";
		//            
		if(!File.Exists(appDBPath))=
		{
			//     
			StartCoroutine(CopyDataBase());
		}
#elif UNITY_IPHONE
		appDBPath = Application.persistentDataPath + "/Test.db";
		//            
		if(!File.Exists(appDBPath))
		{
			//     
			StartCoroutine(CopyDataBase());
		}
#endif
		//"URI=file:"     
		db = new DbAccess ("URI=file:" + appDBPath);
	}

	//     
	IEnumerator CopyDataBase()
	{
		// www  unity      
		//Application.streamingAssetsPath
#if UNITY_IPHONE
		WWW loadDB = new WWW(Application.dataPath
		                     + "/Raw" + "/Test.db");
#elif UNITY_ANDROID
		WWW loadDB = new WWW("jar:file://" + 
		Application.dataPath + "!/assets" + "/Test.db");

#elif UNITY_EDITOR||UNITY_STANDALONE_WIN
		WWW loadDB = new WWW(
			Application.dataPath + "/Test.db");
#endif
		yield return loadDB;
		//     
		File.WriteAllBytes (appDBPath, loadDB.bytes);

	}

	void OnGUI()
	{
		if (GUILayout.Button ("     "))
			CreateDataBase ();
		if (GUILayout.Button ("     "))
			CreateTable ();
		if (GUILayout.Button ("    "))
			InsertData ();
		if (GUILayout.Button ("    "))
			UpdateData ();
		if (GUILayout.Button ("    "))
			DeleteData ();
		if (GUILayout.Button ("    "))
		    FindData ();

		GUILayout.Label ("name:" + name);
		GUILayout.Label ("age:" + age);
		GUILayout.Label ("exp:" + exp);
		GUILayout.Label ("path:" + appDBPath);
	}

	//   
	void CreateTable()
	{
		//     
		CreateDataBase ();
		//      
		db.CreateTable ("role", 
		                new string[]{"id","name",
						"age","lv","exp"}, 
						new string[]{"int","text",
						"int","int","float"});
		//     
		db.CloseSqlConnection ();
	}

	//    
	void InsertData()
	{
		CreateDataBase ();
		//    
		db.InsertInto ("role", new string[]
		               {"1","'  '","18","1","1.2"});
		db.CloseSqlConnection ();

	}

	//    
	void UpdateData()
	{
		CreateDataBase ();
		db.UpdateInto ("role",new string[]{"lv","exp"},
		new string[]{"10","100"},"id","1");
		db.CloseSqlConnection ();
	}

	//    
	void DeleteData()
	{
		CreateDataBase ();
		db.Delete ("role",new string[]{"id","id"},
					new string[]{"1","2"});
		db.CloseSqlConnection ();
	}

	//    
	void FindData()
	{
		CreateDataBase ();
		SqliteDataReader sqReader = 
			db.SelectWhere ("role",
			                new string[]{"name","age","exp"},
			new string[]{"id"},new string[]{"="},
			new string[]{"3"});	
		while(sqReader.Read())
		{
			name = sqReader.GetString
				(sqReader.GetOrdinal("name"));
			age = sqReader.GetInt32
				(sqReader.GetOrdinal("age"));
			exp = sqReader.GetFloat
				(sqReader.GetOrdinal("exp"));
		}
		Debug.Log ("name:" + name);

		db.CloseSqlConnection ();
	}

}

DbAccess, 데이터베이스 링크
using UnityEngine;
using System;
using System.Collections;
using Mono.Data.Sqlite;


public class DbAccess
{
	private SqliteConnection dbConnection;
	private SqliteCommand dbCommand;
	private SqliteDataReader reader;
	public DbAccess (string connectionString)
		
	{
		
		OpenDB (connectionString);
		
	}
	public DbAccess ()
	{
		
	}
	
	public void OpenDB (string connectionString)
		
	{
		try
		{
			dbConnection = new SqliteConnection (connectionString);
			
			dbConnection.Open ();
			
			Debug.Log ("Connected to db,       !");
		}
		catch(Exception e)
		{
			string temp1 = e.ToString();
			Debug.Log(temp1);
		}
		
	}
	
	
	
	public void CloseSqlConnection ()
		
	{
		
		if (dbCommand != null) {
			
			dbCommand.Dispose ();
			
		}
		
		dbCommand = null;
		
		if (reader != null) {
			
			reader.Dispose ();
			
		}
		
		reader = null;
		
		if (dbConnection != null) {
			
			dbConnection.Close ();
			
		}
		
		dbConnection = null;
		
		Debug.Log ("Disconnected from db.     !");
		
	}
	
	
	public SqliteDataReader ExecuteQuery (string sqlQuery)
		
	{
		
		dbCommand = dbConnection.CreateCommand ();
		
		dbCommand.CommandText = sqlQuery;
		
		
		
		reader = dbCommand.ExecuteReader ();
		
		
		
		
		
		return reader;
		
	}
	
	
	public SqliteDataReader ReadFullTable (string tableName)
		
	{
		
		string query = "SELECT * FROM " + tableName;
		
		return ExecuteQuery (query);
		
	}
	
	
	/// 
	///      param tableName=   values=    
	/// 
	public SqliteDataReader InsertInto (string tableName, string[] values)
		
	{
		
		string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
		
		for (int i = 1; i < values.Length; ++i) {
			
			query += ", " + values[i];
			
		}
		
		query += ")";
		
		return ExecuteQuery (query);
		
	}
	
	/// 
	///      param tableName=   cols=     colsvalues=     selectkey=    (  ) selectvalue=    
	/// 
	public SqliteDataReader UpdateInto (string tableName, string []cols,string []colsvalues,string selectkey,string selectvalue)
	{
		
		
		string query = "UPDATE "+tableName+" SET "+cols[0]+" = "+colsvalues[0];
		
		for (int i = 1; i < colsvalues.Length; ++i) {
			
			query += ", " +cols[i]+" ="+ colsvalues[i];
		}
		
		query += " WHERE "+selectkey+" = "+selectvalue+" ";
		
		return ExecuteQuery (query);
	}
	
	/// 
	///      param tableName=   cols=   colsvalues=  
	/// 
	public SqliteDataReader Delete(string tableName,string []cols,string []colsvalues)
	{
		string query = "DELETE FROM "+tableName + " WHERE " +cols[0] +" = " + colsvalues[0];
		
		for (int i = 1; i < colsvalues.Length; ++i) {
			
			query += " or " +cols[i]+" = "+ colsvalues[i];
		}
		return ExecuteQuery (query);
	}
	
	
	public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)
		
	{
		
		if (cols.Length != values.Length) {
			
			throw new SqliteException ("columns.Length != values.Length");
			
		}
		
		string query = "INSERT INTO " + tableName + "(" + cols[0];
		
		for (int i = 1; i < cols.Length; ++i) {
			
			query += ", " + cols[i];
			
		}
		
		query += ") VALUES (" + values[0];
		
		for (int i = 1; i < values.Length; ++i) {
			
			query += ", " + values[i];
			
		}
		
		query += ")";
		
		return ExecuteQuery (query);
		
	}
	

	public SqliteDataReader DeleteContents (string tableName)
		
	{
		
		string query = "DELETE FROM " + tableName;
		
		return ExecuteQuery (query);
		
	}
	
	/// 
	///     param name=   col=    colType=    
	/// 
	public SqliteDataReader CreateTable (string name, string[] col, string[] colType)
		
	{
		
		if (col.Length != colType.Length) {
			
			throw new SqliteException ("columns.Length != colType.Length");
			
		}
		
		string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
		
		for (int i = 1; i < col.Length; ++i) {
			
			query += ", " + col[i] + " " + colType[i];
			
		}
		
		query += ")";
		
		
		return ExecuteQuery (query);
		
	}
	

	/// 
	///      param tableName=   items=     col=     operation=    values=  
	/// 
	public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)
		
	{
		
		if (col.Length != operation.Length || operation.Length != values.Length) {
			
			throw new SqliteException ("col.Length != operation.Length != values.Length");
			
		}
		
		string query = "SELECT " + items[0];
		
		for (int i = 1; i < items.Length; ++i) {
			
			query += ", " + items[i];
			
		}
		
		query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
		
		for (int i = 1; i < col.Length; ++i) {
			
			query += " AND " + col[i] + operation[i] + "'" + values[0] + "' ";
			
		}
		
		
		return ExecuteQuery (query);
			
		
	}
	
}

좋은 웹페이지 즐겨찾기