Unity学习笔记:sqlite数据库

   日期:2020-10-03     浏览:90    评论:0    
核心提示:基本操作using UnityEngine;using System.Collections;using Mono.Data.Sqlite;using System.IO;public class TestDB : MonoBehaviour { /// <summary> /// 数据库 /// </summary> private DbAccess db; /// <summary> /// 数据库路径 /// </summary>

基本操作

using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System.IO;

public class TestDB : MonoBehaviour {

	/// <summary>	/// 数据库	/// </summary>
	private DbAccess db;
	/// <summary>	/// 数据库路径	/// </summary>
	private string appDBPath;

	private string name;
	private int age;
	private float exp;

	/// <summary>	/// 创建/打开数据库	/// </summary>
	private void CreateDataBase()
	{
		#if UNITY_EDITOR || UNITY_STANDALONE_WIN
		appDBPath = Application.streamingAssetsPath + "/Test.db";
		#elif UNITY_ANDROID || UNITY_IPHONE
		appDBPath = Application.persistentDataPath + "/Test.db";
		if(!File.Exists(appDBPath)){
			StartCoroutine(CopyDataBase());
		}
		#endif
		db = new DbAccess ("URI=file:" + appDBPath);
	}

	/// <summary>	/// 拷贝数据库	/// </summary>
	/// <returns>数据库.</returns>
	private IEnumerator CopyDataBase()
	{
		WWW loadDB = new WWW (Application.streamingAssetsPath + "/Test.db");
		yield return loadDB;
		File.WriteAllBytes (appDBPath,loadDB.bytes);
	}

	/// <summary>	/// 创建表	/// </summary>
	private void CreateTable()
	{
		CreateDataBase ();
		db.CreateTable ("Role",new string[] {"id","name","age","lv","exp"},
			new string[] {"int","text","int","int","float"});
		db.CloseSqlConnection ();
	}

	/// <summary>	/// 插入数据	/// </summary>
	private void InsertData()
	{
		CreateDataBase ();
		db.InsertInto ("Role",new string[] {"1","'张三'","18","10","100"});
		db.InsertInto ("Role",new string[] {"2","'李四'","20","2","2.2"});
		db.InsertInto ("Role",new string[] {"3","'老王'","19","3","3.3"});
		db.CloseSqlConnection ();
	}

	/// <summary>	/// 更新数据	/// </summary>
	private void UpdateData()
	{
		CreateDataBase ();
		db.UpdateInto ("Role",new string[] {"name","lv","exp"},
			new string[] {"'test'","1","1.1"},"id","1");
		db.CloseSqlConnection ();
	}

	/// <summary>	/// 删除数据	/// </summary>
	private void DeleteData()
	{
		CreateDataBase ();
		db.Delete ("Role",new string[] {"id","id"},new string[] {"1","3"});
		db.CloseSqlConnection ();
	}

	/// <summary>	/// 删除表中全部数据	/// </summary>
	private void DeleteAllData()
	{
		CreateDataBase ();
		db.DeleteContents ("Role");
		db.CloseSqlConnection ();
	}

	/// <summary>	/// 查询数据	/// </summary>
	private void FindData()
	{
		CreateDataBase ();
		SqliteDataReader sqReader = db.SelectWhere ("Role",new string[] {
			"name","age","exp"},new string[] {"id"},new string[] {"="},
			new string[] {"1"});
		sqReader.Read ();
		name = sqReader.GetString (sqReader.GetOrdinal("name"));
		age = sqReader.GetInt32 (sqReader.GetOrdinal("age"));
		exp = sqReader.GetFloat (sqReader.GetOrdinal("exp"));
		db.CloseSqlConnection ();
	}

	private void SelectData()
	{
		CreateDataBase ();
//		SqliteDataReader sqReader = db.ReadFullTable ("Role");
//		SqliteDataReader sqReader = db.SelectOrderASC ("Role","age");
		SqliteDataReader sqReader = db.SelectOrderDESC ("Role","age");
		while(sqReader.Read())
		{
			Debug.Log (sqReader.GetInt32(sqReader.GetOrdinal("id")) + " " +
				sqReader.GetString(sqReader.GetOrdinal("name")) + " " + 
				sqReader.GetInt32(sqReader.GetOrdinal("age")) + " " + 
				sqReader.GetInt32(sqReader.GetOrdinal("lv")) + " " + 
				sqReader.GetFloat(sqReader.GetOrdinal("exp")));
		}
		db.CloseSqlConnection ();
	}

	private void OnGUI()
	{
		if (GUILayout.Button ("创建表"))
			CreateTable ();
		if (GUILayout.Button ("插入数据"))
			InsertData ();
		if (GUILayout.Button ("更新数据"))
			UpdateData ();
		if (GUILayout.Button ("删除数据"))
			DeleteData ();
		if (GUILayout.Button ("删除表中全部数据"))
			DeleteAllData ();
		if (GUILayout.Button ("读取数据"))
			FindData ();
		if (GUILayout.Button ("多种读取数据"))
			SelectData ();
		#if HTC
		if (GUILayout.Button ("充值"))
			FindData ();
		#endif
		#if OC
		if (GUILayout.Button ("充值"))
			SelectData ();
		#endif
		GUILayout.Label ("name:" + name);
		GUILayout.Label ("age:" + age);
		GUILayout.Label ("exp:" + exp);
	
	}
}

工具类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;
		
	}
	
	/// <summary>
	/// 查询表中全部数据 param tableName=表名 
	/// </summary>
	public SqliteDataReader ReadFullTable (string tableName)
		
	{
		
		string query = "SELECt * FROM " + tableName;
		
		return ExecuteQuery (query);
		
	}
	
	
	/// <summary>
	/// 插入数据 param tableName=表名 values=插入数据内容
	/// </summary>
	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);
		
	}
	
	/// <summary>
	/// 更新数据 param tableName=表名 cols=更新字段 colsvalues=更新内容 selectkey=查找字段(主键) selectvalue=查找内容
	/// </summary>
	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);
	}
	
	/// <summary>
	/// 删除数据 param tableName=表名 cols=字段 colsvalues=内容
	/// </summary>
	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);
	}
	
	/// <summary>
	/// 插入数据 param tableName=表名 cols=插入字段 value=插入内容
	/// </summary>
	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);
		
	}
	
	
	/// <summary>
	/// 删除表中全部数据
	/// </summary>
	public SqliteDataReader DeleteContents (string tableName)
		
	{
		
		string query = "DELETE FROM " + tableName;
		
		return ExecuteQuery (query);
		
	}
	
	/// <summary>
	/// 创建表 param name=表名 col=字段名 colType=字段类型
	/// </summary>
	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);
		
	}
	
	
	
	
	
	/// <summary>
	/// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段 operation=运算符 values=内容
	/// </summary>
	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);
	}

	/// <summary>
	/// 查询表
	/// </summary>
	public SqliteDataReader Select(string tableName, string col, string values)
	{
		string query = "SELECT * FROM " + tableName  + " WHERe " + col + " = " + values;
		return ExecuteQuery (query);
	}

	public SqliteDataReader Select(string tableName, string col,string operation, string values)
	{
		string query = "SELECT * FROM " + tableName  + " WHERe " + col + operation + values;
		return ExecuteQuery (query);
	}

	/// <summary>
	/// 升序查询
	/// </summary>
	public SqliteDataReader SelectOrderASC (string tableName,string col)
	{
		string query = "SELECT * FROM " + tableName  + " ORDER BY " + col + " ASC";
		return ExecuteQuery (query);
	}

	/// <summary>
	/// 降序查询
	/// </summary>
	public SqliteDataReader SelectOrderDESC (string tableName,string col)
	{
		string query = "SELECT * FROM " + tableName  + " ORDER BY " + col + " DESC";
		return ExecuteQuery (query);
	}

	/// <summary>
	/// 查询表行数
	/// </summary>
	public SqliteDataReader SelectCount(string tableName)
	{
		string query = "SELECT COUNT(*) FROM " + tableName;
		return ExecuteQuery (query);
	}
}

 

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服