unity sqlite資料庫操作
阿新 • • 發佈:2019-01-26
首先在專案中新增兩個動態連結庫Mono.Data.Sqlite.dll和System.Data.dll
建立資料庫管理指令碼,該指令碼用來直接操作資料庫的操作,可以看作是對資料庫操作的sql語句的封裝。
using UnityEngine;
using System.Data;
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 ()
{
}
/// <summary>
/// 開啟資料庫
/// </summary>
/// <param name="connectionString">Connection string.</param>
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);
}
}
/// <summary>
/// 關閉資料庫
/// </summary>
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.");
}
/// <summary>
/// 執行sql語句
/// </summary>
/// <returns>The query.</returns>
/// <param name="sqlQuery">查詢語句.</param>
public SqliteDataReader ExecuteQuery (string sqlQuery)
{
Debug.Log ("sql="+sqlQuery);
dbCommand = dbConnection.CreateCommand ();
dbCommand.CommandText = sqlQuery;
reader = dbCommand.ExecuteReader ();
return reader;
}
/// <summary>
/// 查詢整個table的資料
/// </summary>
/// <returns>The full table.</returns>
/// <param name="tableName">表名.</param>
public SqliteDataReader ReadFullTable (string tableName)
{
string query = "SELECT * FROM " + tableName;
return ExecuteQuery (query);
}
/// <summary>
/// 插入資料
/// </summary>
/// <returns>The into.</returns>
/// <param name="tableName">表名</param>
/// <param name="values">需要插入的欄位內容,注意字串需要新增單引號 如 ‘name’</param>
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>
/// 更新table內容
/// </summary>
/// <returns>The into.</returns>
/// <param name="tableName">Table 名稱.</param>
/// <param name="cols">需要更新的欄位名稱陣列.</param>
/// <param name="colsvalues">需要更新的欄位對應的值.</param>
/// <param name="selectkey">更新依據的欄位.</param>
/// <param name="selectvalue">更新依據欄位對應的值</param>
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>
/// 根據刪除條件,刪除對應的資料
/// </summary>
/// <param name="tableName">Table 名稱.</param>
/// <param name="cols">欄位陣列.</param>
/// <param name="colsvalues">欄位陣列對應的值.</param>
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>
/// 插入資料,只插入部分欄位的資料
/// </summary>
/// <returns>The into specific.</returns>
/// <param name="tableName">Table 名稱.</param>
/// <param name="cols">需要插入的欄位陣列.</param>
/// <param name="values">需要插入的欄位陣列對應的值.</param>
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>
/// <returns>The contents.</returns>
/// <param name="tableName">Table name.</param>
public SqliteDataReader DeleteContents (string tableName)
{
string query = "DELETE FROM " + tableName;
return ExecuteQuery (query);
}
/// <summary>
/// 建立一個數據表
/// </summary>
/// <returns>The table.</returns>
/// <param name="name">Name.</param>
/// <param name="col">Col.</param>
/// <param name="colType">Col type.</param>
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>
/// 根據條件篩選資料
/// </summary>
/// <returns>The where.</returns>
/// <param name="tableName">Table name.</param>
/// <param name="items">需要篩選的欄位.</param>
/// <param name="col">篩選條件的健.</param>
/// <param name="operation">篩選符號,如 >,<,= </param>.</param>
/// <param name="values">篩選條件的值.</param>
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);
}
}
呼叫資料庫方法,將該指令碼掛載到場景中,完成對資料庫管理指令碼封裝方法的呼叫。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;
public class SqliteTest1 : MonoBehaviour {
string dbPath;
string dbName;
DbAccess db;
// Use this for initialization
void Start () {
dbName="userInfo.db";
dbPath=getPath ();
if (!System.IO.File.Exists (dbPath)) {
//建立資料庫
db = new DbAccess ("data source=" + dbPath);
//建立資料庫表,與欄位
SqliteDataReader reader= db.CreateTable ("user", new string[]{ "name", "age", "sex", "adress" }, new string[]{ "text", "integer", "text", "text" });
if (reader != null)
Debug.Log ("create tabel success");
else
Debug.LogError ("create tabel fail");
} else db = new DbAccess ("data source=" + dbPath);
//關閉物件
//db.CloseSqlConnection();
}
string getPath(){
string path=Application.dataPath+"/"+dbName;
#if UNITY_EDITOR
path=Application.streamingAssetsPath+"/"+dbName;
if (!System.IO.Directory.Exists (path)){
// System.IO.DirectoryInfo dir=new System.IO.DirectoryInfo(Application.streamingAssetsPath);
// dir.Create();
System.IO.Directory.CreateDirectory(Application.streamingAssetsPath);
}
#elif UNITY_ANDROID
path=Application.persistentDataPath+"/"+dbName;
#elif UNITY_IOS
path=Application.persistentDataPath+"/"+dbName;
#endif
Debug.Log (Application.dataPath);
Debug.Log (Application.persistentDataPath);
Debug.Log (Application.temporaryCachePath);
Debug.Log (path);
return path;
}
void OnDestroy(){
Debug.Log ("<color=#00ff00>close database</color>");
//關閉物件
db.CloseSqlConnection();
}
void InsertData(){
db.InsertInto ("user", new string[]{ "'zhangsan'","11","'man'","'beijing'"});
db.InsertInto ("user", new string[]{ "'lisi'","11","'woman'","'huoying'"});
}
void UpdateData(){
db.UpdateInto ("user",new string[]{ "age", "sex"}, new string[]{ "82", "'woman'" },"name","'zhangsan'");
}
void DeleteData(){
db.Delete ("user",new string[]{ "age", "sex"}, new string[]{ "82", "'woman'" });
}
void QueryData(){
string query = "select * from user where name='zhangsan'";
SqliteDataReader reader=db.ExecuteQuery (query);
while(reader.Read()){
Debug.Log ("name="+reader["name"]);
Debug.Log ("age="+reader["age"]);
Debug.Log ("sex="+reader["sex"]);
Debug.Log ("adress="+reader["adress"]);
}
}
void SelectData(){
// "select (name,age,sex) from user where age > 20";
SqliteDataReader reader= db.SelectWhere ("user",new string[]{"name","age","sex"},new string[]{"age"},new string[]{">"},new string[]{"20"});
while(reader.Read()){
Debug.Log ("name="+reader["name"]);
Debug.Log ("age="+reader["age"]);
Debug.Log ("sex="+reader["sex"]);
}
}
void OnGUI() {
if (GUI.Button (new Rect (10, 20, 100, 40), "insert data")) {
InsertData ();
} else if (GUI.Button (new Rect (10, 80, 100, 40), "delete data")) {
DeleteData ();
} else if (GUI.Button (new Rect (10, 120, 100, 40), "updata data")) {
UpdateData ();
} else if (GUI.Button (new Rect (10, 180, 100, 40), "query data")) {
QueryData ();
} else if (GUI.Button (new Rect (10, 250, 100, 40), "select data")) {
SelectData ();
}
else if (GUI.Button (new Rect (180, 20, 100, 40), "query all data")) {
SqliteDataReader reader= db.ReadFullTable("user");
int count = 0;
while(reader.Read()){
count++;
// Debug.Log ("name="+reader["name"]);
// Debug.Log ("age="+reader["age"]);
// Debug.Log ("sex="+reader["sex"]);
// Debug.Log ("adress="+reader["adress"]);
Debug.Log ("name=" + reader ["name"] + ",age=" + reader ["age"] + ",sex=" + reader ["sex"] + ",adress=" + reader ["adress"]);
}
Debug.Log ("count="+count);
}
}
}
資源導包時報錯:ArgumentException: The Assembly System.Configuration is referenced by System.Data (‘Assets/plugins/System.Data.dll’). But the dll is not allowed to be included or could not be found.
解決方法:在PlaySettings--other setting 中修改Api Compatibility Level 改成.NET 2.0
下載內容是一個unity資源包,拖到專案中之後,建立一個空場景,把SqliteTest1.cs掛載到相機上面,就可以執行測試。