using OTSModelSharp.DTLBase;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OTSModelSharp.DTLBase
{
///
/// SQLite 操作类
///
public class SQLiteHelper
{
///
/// 数据库连接字符串
///
private string connectionString;
///
/// SQL命令定义
///
private SQLiteCommand dbCommand;
private SQLiteDataAdapter dataAdapter;
///
/// 数据读取定义
///
private SQLiteDataReader dataReader;
private DataTable dt;
private NLog.Logger log;
///
/// 构造函数
///
/// 连接SQLite库字符串
public SQLiteHelper(string a_sFileName)
{
log = NLog.LogManager.GetCurrentClassLogger();
connectionString = "data source='" + a_sFileName + "'" + ";Version=3;";
}
///
/// 根据数据源、密码、版本号设置连接字符串。
///
/// 数据源。
/// 密码。
/// 版本号(缺省为3)。
public void SetConnectionString(string datasource, string password, int version = 3)
{
connectionString = string.Format("Data Source={0};Version={1};password={2}",
datasource, version, password);
}
public SQLiteConnection GetDBConnection()
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
return connection;
}
///
/// 创建一个数据库文件。如果存在同名数据库文件,则会覆盖。
///
/// 数据库文件名。为null或空串时不创建。
/// (可选)数据库密码,默认为空。
///
public static void CreateNewDatabase(string dbName)
{
if (!string.IsNullOrEmpty(dbName))
{
try { SQLiteConnection.CreateFile(dbName); }
catch (Exception) { throw; }
}
}
///
/// 删除指定的数据库文件
///
///
public void DeleteDataBase(string basename)
{
try
{
if (System.IO.File.Exists(basename))
{
System.IO.File.Delete(basename);
}
}
catch (Exception)
{ throw; }
}
///
/// 执行SQL命令
///
/// The query.
/// SQL命令字符串
public DataTable ExecuteQuery(string sql, params SQLiteParameter[] parameters)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
if (parameters.Length != 0)
{
command.Parameters.AddRange(parameters);
}
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
DataTable data = new DataTable();
try { adapter.Fill(data); }
catch (Exception) { throw; }
return data;
}
}
}
///
/// 对SQLite数据库执行增删改操作,返回受影响的行数。
///
/// 要执行的增删改的SQL语句。
/// 执行增删改语句所需要的参数,参数必须以它们在SQL语句中的顺序为准。
///
///
public int ExecuteNonQuery(string sql, params SQLiteParameter[] parameters)
{
int affectedRows = 0;
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand command = new SQLiteCommand(connection))
{
try
{
connection.Open();
command.CommandText = sql;
if (parameters.Length != 0)
{
command.Parameters.AddRange(parameters);
}
affectedRows = command.ExecuteNonQuery();
}
catch (Exception) { throw; }
}
}
return affectedRows;
}
public int ExecuteNonQueryForTransaction(string sql, SQLiteConnection conn, params SQLiteParameter[] parameters)
{
int affectedRows = 0;
using (SQLiteCommand command = new SQLiteCommand(conn))
{
try
{
command.CommandText = sql;
if (parameters.Length != 0)
{
command.Parameters.AddRange(parameters);
}
affectedRows = command.ExecuteNonQuery();
}
catch (Exception) { throw; }
}
return affectedRows;
}
///
/// 批量处理数据操作语句。
///
/// SQL语句集合。
///
public void ExecuteNonQueryBatch(List> list)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
try { conn.Open(); }
catch { throw; }
using (SQLiteTransaction tran = conn.BeginTransaction())
{
using (SQLiteCommand cmd = new SQLiteCommand(conn))
{
try
{
foreach (var item in list)
{
cmd.CommandText = item.Key;
if (item.Value != null)
{
cmd.Parameters.AddRange(item.Value);
}
cmd.ExecuteNonQuery();
}
tran.Commit();
}
catch (Exception) { tran.Rollback(); throw; }
}
}
}
}
///
/// 执行一个查询语句,返回一个关联的SQLiteDataReader实例。
///
/// 要执行的查询语句。
/// 执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准。
///
///
public SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] parameters)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand command = new SQLiteCommand(sql, connection);
try
{
if (parameters.Length != 0)
{
command.Parameters.AddRange(parameters);
}
connection.Open();
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception) { throw; }
}
///
/// 执行查询语句,并返回第一个结果。
///
/// 查询语句。
/// 查询结果。
///
public object ExecuteScalar(string sql, params SQLiteParameter[] parameters)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(conn))
{
try
{
conn.Open();
cmd.CommandText = sql;
if (parameters.Length != 0)
{
cmd.Parameters.AddRange(parameters);
}
return cmd.ExecuteScalar();
}
catch (Exception) { throw; }
}
}
}
///
/// 读取整张数据表
///
/// The full table.
/// 数据表名称
public DataTable ReadFullTable(string tableName,string order)
{
string queryString = "SELECT * FROM " + tableName+" order by "+ order;
return ExecuteQuery(queryString);
}
///
/// /// 执行一个查询语句,返回一个包含查询结果的DataTable
/// ///
/// /// 要执行的查询语句
/// /// 执行查询语句的参数
/// ///
public DataTable ExecuteDataTable(string sql, params SQLiteParameter[] parameters)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
using (SQLiteCommand command = new SQLiteCommand(sql, conn))
{
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
return data;
}
}
}
///
/// /// tbale转list
/// ///
/// ///
/// ///
public List TableToList(DataTable table) where T : class, new()
{
var result = new List();
var propertys = typeof(T).GetProperties();
foreach (DataRow dr in table.Rows)
{
var item = new T();
result.Add(item);
foreach (var pi in propertys)
{
if (!table.Columns.Contains(pi.Name))
continue;
var value = dr[pi.Name];
if (value is DBNull || value == null)
continue;
if (value.GetType().ToString() == "System.Int64")
{
pi.SetValue(item, Convert.ToInt32(value));
}
else
{
pi.SetValue(item, value);
}
}
}
return result;
}
///
/// /// tbale转list
/// ///
/// ///
/// ///
public List RowsToList(DataRow[] table) where T : class, new()
{
var result = new List();
var propertys = typeof(T).GetProperties();
foreach (DataRow dr in table)
{
var item = new T();
result.Add(item);
foreach (var pi in propertys)
{
if (!dr.Table.Columns.Contains(pi.Name))
continue;
var value = dr[pi.Name];
if (value is DBNull || value == null)
continue;
if (value.GetType().ToString() == "System.Int64")
{
pi.SetValue(item, Convert.ToInt32(value));
}
else
{
pi.SetValue(item, value);
}
}
}
return result;
}
///
/// 向指定数据表中插入数据
///
/// The values.
/// 数据表名称
/// 插入的数值
public DataTable InsertValues(string tableName, string[] values)
{
//获取数据表中字段数目
int fieldCount = ReadFullTable(tableName,"").Columns.Count;
//当插入的数据长度不等于字段数目时引发异常
if (values.Length != fieldCount)
{
throw new SQLiteException("values.Length!=fieldCount");
}
string queryString = "INSERT INTO " + tableName + " VALUES (" + "'" + values[0] + "'";
for (int i = 1; i < values.Length; i++)
{
queryString += ", " + "'" + values[i] + "'";
}
queryString += " )";
return ExecuteQuery(queryString);
}
///
/// 更新指定数据表内的数据
///
/// The values.
/// 数据表名称
/// 字段名
/// 字段名对应的数据
/// 关键字
/// 关键字对应的值
/// 运算符:=,<,>,...,默认“=”
public DataTable UpdateValues(string tableName, string[] colNames, string[] colValues, string key, string value, string operation = "=")
{
//当字段名称和字段数值不对应时引发异常
if (colNames.Length != colValues.Length)
{
throw new SQLiteException("colNames.Length!=colValues.Length");
}
string queryString = "UPDATE " + tableName + " SET " + colNames[0] + "=" + "'" + colValues[0] + "'";
for (int i = 1; i < colValues.Length; i++)
{
queryString += ", " + colNames[i] + "=" + "'" + colValues[i] + "'";
}
queryString += " WHERE " + key + operation + "'" + value + "'";
return ExecuteQuery(queryString);
}
///
/// 删除指定数据表内的数据
///
/// The values.
/// 数据表名称
/// 字段名
/// 字段名对应的数据
public DataTable DeleteValuesOR(string tableName, string[] colNames, string[] colValues, string[] operations)
{
//当字段名称和字段数值不对应时引发异常
if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
{
throw new SQLiteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
}
string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
for (int i = 1; i < colValues.Length; i++)
{
queryString += "OR " + colNames[i] + operations[0] + "'" + colValues[i] + "'";
}
return ExecuteQuery(queryString);
}
///
/// 删除指定数据表内的数据
///
/// The values.
/// 数据表名称
/// 字段名
/// 字段名对应的数据
public DataTable DeleteValuesAND(string tableName, string[] colNames, string[] colValues, string[] operations)
{
//当字段名称和字段数值不对应时引发异常
if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
{
throw new SQLiteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
}
string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
for (int i = 1; i < colValues.Length; i++)
{
queryString += " AND " + colNames[i] + operations[i] + "'" + colValues[i] + "'";
}
return ExecuteQuery(queryString);
}
///
/// 创建数据表
/// +
/// The table.
/// 数据表名
/// 字段名
/// 字段名类型
public int CreateTable(TableModel table)
{
StringBuilder builder = new StringBuilder();
builder.Append("CREATE TABLE IF NOT EXISTS " + table.TableName+"(");
int ind = 0;
foreach (var item in table.columns)
{
builder.Append(item.ColumName + " " + item.ColumType + " " + (item.IsPrimarykey ? "PRIMARY KEY" : ""));
if (++ind == table.columns.Count)
{
builder.Append(")");
}
else
{
builder.Append(",");
}
}
return ExecuteNonQuery(builder.ToString());
}
///
/// 判断表存在
///
///
///
public bool IsExist(string tableName)
{
string queryString = "select count(*) from sqlite_master where [type]='table' and [name]='"+ tableName + "'" ;
Int64 i = (Int64)ExecuteScalar(queryString);
return i > 0 ? true : false;
}
///
/// 删除数据库表
///
///
///
public bool DeleteTable(string tableName)
{
string queryString = "drop table " + tableName;
return ExecuteNonQuery(queryString)>0?true:false;
}
///
/// 删除数据库表数据
///
///
///
public bool RemoveAllRows(string tableName)
{
string queryString = "DELETE FROM " + tableName;
return ExecuteNonQuery(queryString) > 0 ? true : false;
}
///
/// Reads the table.
///
/// The table.
/// Table name.
/// Items.
/// Col names.
/// Operations.
/// Col values.
public DataTable ReadTable(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues)
{
string queryString = "SELECT " + items[0];
for (int i = 1; i < items.Length; i++)
{
queryString += ", " + items[i];
}
queryString += " FROM " + tableName + " where 1=1";
//+ " WHERE " + colNames[0] + " " + operations[0] + " " + colValues[0];
for (int i = 0; i < colNames.Length; i++)
{
queryString += " AND " + colNames[i] + " " + operations[i] + " " + colValues[0] + " ";
}
return ExecuteQuery(queryString);
}
}
}