using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
namespace IOTContainer.SQLite
{
public class SQLiteAdapter : IDisposable
{
#region 构造函数
///
/// 初始化适配器
///
/// 数据库文件路径
/// 是否只读
public SQLiteAdapter(string databasePath, bool isReadOnly = false)
{
if (string.IsNullOrWhiteSpace(databasePath))
{
throw new Exception("Database File Cannot be Null Or White Space!");
}
this.DatabasePath = databasePath;
this.IsReadOnly = isReadOnly;
this._password = null;
this._connection = null;
}
///
/// 初始化适配器
///
/// 数据库文件路径
/// 数据库密码
/// 是否只读
public SQLiteAdapter(string databasePath, string password, bool isReadOnly = false)
{
if (string.IsNullOrWhiteSpace(databasePath))
{
throw new Exception("Database File Cannot be Null Or White Space!");
}
this.DatabasePath = databasePath;
this._password = password;
this.IsReadOnly = isReadOnly;
this._connection = null;
}
#endregion
#region 字段属性
///
/// 密码
///
private string _password;
///
/// 数据库文件
///
public string DatabasePath { get; private set; }
///
/// 是否只读
///
public bool IsReadOnly { get; }
private string DataSource
{
get
{
StringBuilder builder = new StringBuilder();
builder.Append(string.Format("Data Source={0}", this.DatabasePath));
if (!string.IsNullOrEmpty(_password))
{
builder.Append(string.Format(";Password={0}", this._password));
}
if (IsReadOnly)
{
builder.Append(string.Format(";Read Only={0}", this.IsReadOnly));
}
return builder.ToString();
}
}
///
/// 连接
///
private SQLiteConnection _connection;
///
/// 获取是否连接
///
public bool IsConnect { get; private set; }
///
/// 获取是否销毁
///
public bool IsDispose { get; private set; }
#endregion
#region 对外函数
///
/// 连接数据库
///
public void Connection()
{
try
{
if (IsDispose)
{
throw new Exception("Adapter Is Dispose!");
}
if (this.IsConnect)
{
throw new Exception("Adapter Is Aready Connect!");
}
this._connection = new SQLiteConnection(this.DataSource);
this._connection.Open();
this.IsConnect = true;
}
catch (Exception e)
{
throw e;
}
}
///
/// 获取执行器
///
/// 执行器
public SQLiteActuator GetActuator()
{
if (IsDispose)
{
throw new Exception("Adapter Is Dispose!");
}
if (!this.IsConnect)
{
throw new Exception("Adapter Is Not Connect!");
}
return new SQLiteActuator(new SQLiteCommand(this._connection));
}
///
/// 关闭连接
///
public void Close()
{
if (!this.IsConnect)
{
throw new Exception("Adapter Is Not Connect!");
}
this.IsConnect = false;
this._connection.Close();
this._connection.Dispose();
this._connection = null;
}
///
/// 销毁
///
public void Dispose()
{
this.IsDispose = true;
if (this.IsConnect)
{
this.Close();
}
this._password = null;
this.DatabasePath = null;
}
#endregion
}
}