您的位置:首页 > 移动开发 > Unity3D

Unity简易数据库之Sqlite

2016-02-29 16:44 781 查看
1:Sqlite类

2:Sqlite读取案例

using UnityEngine;

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

public class DbAccess
{

public SqliteConnection dbConnection;

public SqliteCommand dbCommand;

public SqliteDataReader reader;

public DbAccess(string connectionString)
{

OpenDB("Data Source=" + connectionString, "");

}
public DbAccess(string connectionString,string password)
{

OpenDB("Data Source=" + connectionString, password);

}
public DbAccess()
{

}

public void OpenDB(string connectionString, string password)
{
try
{
/***********/
if (!File.Exists(connectionString.Substring(12, connectionString.Length - 12)))
{
SqliteConnection.CreateFile(connectionString.Substring(12, connectionString.Length - 12));
}
/***********/
dbConnection = new SqliteConnection(connectionString);
if (!string.IsNullOrEmpty(password))
{
dbConnection.SetPassword(password);
}
dbConnection.Open();

// Debug.Log("Connected to db :" + connectionString);
}
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.");

}

/// <summary>
/// 直接用的方法 推荐!!!
/// </summary>
/// <param name="sqlQuery"></param>
/// <returns></returns>
public SqliteDataReader ExecuteQuery(string sqlQuery)
{
// Debug.Log("SQL: " + 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);

}

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);

}

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 + " ";
Debug.Log("UpdateInto:" + query);
return ExecuteQuery(query);
}

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);

}

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>
/// 这里 查询条件 "AND" 组合?
/// 查询语句:SELECT otherId, otherName, content, time FROM talkHistory WHERE otherId='002' AND otherName='sukia2'
/// </summary>
/// <param name="tableName"></param>
/// <param name="items"></param>
/// <param name="col"></param>
/// <param name="operation"></param>
/// <param name="values"></param>
/// <returns></returns>
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[i] + "' ";

}

return ExecuteQuery(query);

}

/// <summary>
/// 修改密码
/// </summary>
/// <paramname="path"></param>
/// <param name="newPassword"></param>
/// <param name="oldPassword">没有密码时为空</param>
public bool ChangePassword(string path, string newPassword, string oldPassword)
{
try
{
SqliteConnection con = new SqliteConnection(SQLiteConnectionString.GetConnectionString(path, oldPassword));
Debug.Log(SQLiteConnectionString.GetConnectionString(path, oldPassword));
con.Open();
con.ChangePassword(newPassword);
con.Close();
}
catch (Exception e)
{
string temp1 = e.ToString();
Debug.Log(temp1);
}
return true;
}
/// <summary>
/// 生成SQLite连接字符串
/// </summary>
public static class SQLiteConnectionString
{
public static string GetConnectionString(string path)
{
return GetConnectionString(path, null);
}
public static string GetConnectionString(string path, string password)
{
if (string.IsNullOrEmpty(password))
{
return "Data Source=" + path;

}
else
{
return "Data Source=" + path + ";Password=" + password;
}
}
}

}
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using Mono.Data.Sqlite;

public class DB_Sqlite : MonoBehaviour
{
protected static DB_Sqlite instance;
public static DB_Sqlite Instance
{
get
{
if (instance == null)
{
instance = (DB_Sqlite)FindObjectOfType(typeof(DB_Sqlite));

if (instance == null)
{
Debug.LogError("An instance of
a11d
" + typeof(DB_Sqlite) +
" is needed in the scene, but there is none.");
}
}

return instance;
}
}
public struct TalkMsg
{
public string Id;
public string Name;
public string Type;
public string Content;
public string Time;
/// <summary>
/// 0表示对方说的,1表示我说的
/// </summary>
public string hisormy;
public TalkMsg(string a, string b, string c, string d, string e, string f)
{
this.Id = a;
this.Name = b;
this.Type = c;
this.Content = d;
this.Time = e;
this.hisormy = f;
}
}

public void Save_TalkMsg(TalkMsg msg)
{
string appDBPath = Application.dataPath + "/StreamingAssets/TalkHistory/" + Global.userId + ".db";
string password = "Steven";
DbAccess db = new DbAccess(appDBPath, password);
SqliteCommand mDbCmd = db.dbConnection.CreateCommand();
mDbCmd.CommandText = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='talkHistory';";
if (0 == Convert.ToInt32(mDbCmd.ExecuteScalar()))
{
//table - Student does not exist.
// db.dbConnection.ChangePassword("123456");
db.CreateTable("talkHistory", new string[] { "id", "name", "type", "content", "time", "hisormy" }, new string[] { "text", "text", "text", "text", "text", "text" });
}
else
{
//table - Student does exist.
}

db.InsertInto("talkHistory", new string[] { "'" + msg.Id + "'", "'" + msg.Name + "'", "'" + msg.Type + "'", "'" + msg.Content + "'", "'" + msg.Time + "'", "'" + msg.hisormy + "'" });
db.CloseSqlConnection();
}
public List<TalkMsg> MsgsForSomeOne(string id)
{
List<TalkMsg> list = new List<TalkMsg>();
string appDBPath = Application.dataPath + "/StreamingAssets/TalkHistory/" + Global.userId + ".db";
if (!File.Exists(appDBPath))
{
return list;
}
string password = "Steven";
DbAccess db = new DbAccess(appDBPath, password);
using (SqliteDataReader sqReader = db.ExecuteQuery("SELECT id, name, type, content,time,hisormy FROM talkHistory WHERE id='" + id + "'"))
{

while (sqReader.Read())
{
TalkMsg msg = new TalkMsg();
msg.Id = sqReader.GetString(sqReader.GetOrdinal("id"));
msg.Name = sqReader.GetString(sqReader.GetOrdinal("name"));
msg.Type = sqReader.GetString(sqReader.GetOrdinal("type"));
msg.Content = sqReader.GetString(sqReader.GetOrdinal("content"));
msg.Time = sqReader.GetString(sqReader.GetOrdinal("time"));
msg.hisormy = sqReader.GetString(sqReader.GetOrdinal("hisormy"));
list.Add(msg);
}
sqReader.Close();
}
return list;
}
public void DeleteSomeOne(string id)
{
try
{
string appDBPath = Application.dataPath + "/StreamingAssets/TalkHistory/" + Global.userId + ".db";
string password = "Steven";
DbAccess db = new DbAccess(appDBPath, password);
db.ExecuteQuery("DELETE FROM talkHistory WHERE id='" + id + "'");
// db.Delete("talkHistory", new string[] { "id" }, new string[] { "'" + id + "'"});
db.CloseSqlConnection();
}
catch
{
return;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity C# 数据库 sqlite