using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MV485.helper
{
public abstract class SQLiteHelper
{
private static string DBFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mv485.db");
//private static string connectionString = $"data source={DBFileName}";
private static string connectionString = $"Data Source={DBFileName};Version=3;";
///
/// 获取连接字符串
///
public static string GetConnStr()
{
return connectionString;
}
///
/// 创建本地库连接
///
/// 返回本地库连接
public static SQLiteConnection CreateConn()
{
return new SQLiteConnection(connectionString);
}
// 获取 SQLite 数据库连接
public static SQLiteConnection GetConnection()
{
return new SQLiteConnection(connectionString);
}
// 执行 SQL 命令(不返回结果集,仅返回受影响的行数)
public static int ExecuteNonQuery(string sql, SQLiteParameter[] parameters)
{
using (SQLiteConnection conn = GetConnection())
{
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
// 添加参数
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
// 执行 SQL 语句并返回受影响的行数
return cmd.ExecuteNonQuery();
}
}
}
// 支持事务的 ExecuteNonQuery
public static int ExecuteNonQuery(string sql, SQLiteParameter[] parameters, SQLiteTransaction transaction)
{
using (SQLiteCommand cmd = new SQLiteCommand(sql, transaction.Connection, transaction))
{
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
return cmd.ExecuteNonQuery();
}
}
///
/// 执行查询语句,返回一个值
///
/// SQL语句
/// 返回的值
public static int ExecuteSel(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
{
try
{
connection.Open();
return Convert.ToInt32(cmd.ExecuteScalar());
}
catch (SQLiteException e)
{
throw new Exception("Error executing SELECT query.", e);
}
}
}
///
/// 执行SQL语句,返回影响的记录数
///
/// SQL语句
/// 影响的记录数
public static int ExecuteSql(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
{
try
{
connection.Open();
return cmd.ExecuteNonQuery();
}
catch (SQLiteException e)
{
throw new Exception("Error executing SQL.", e);
}
}
}
///
/// 执行一组SQL语句
///
/// SQL语句集合
/// 成功返回True,失败返回False
public static bool ExecuteSql(List SQLList)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (SQLiteTransaction transaction = connection.BeginTransaction())
{
try
{
foreach (var SQL in SQLList)
{
using (SQLiteCommand cmd = new SQLiteCommand(SQL, connection))
{
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
return true;
}
catch (SQLiteException e)
{
transaction.Rollback();
throw new Exception("Transaction failed, rolled back.", e);
}
}
}
}
///
/// 执行SQL语句,带参数
///
/// SQL语句
/// SQL参数
/// 影响的记录数
public static int ExecuteSql(string SQLString, SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
return cmd.ExecuteNonQuery();
}
catch (SQLiteException e)
{
throw new Exception("Error executing parameterized SQL.", e);
}
}
}
private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
if (cmdParms != null)
{
foreach (SQLiteParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
///
/// 删除指定表的所有数据
///
/// 指定的表名
/// 影响的记录数
public static int DelTableData(string TableName)
{
string SQLString = $"DELETE FROM '{TableName}'";
return ExecuteSql(SQLString);
}
///
/// 执行查询语句,返回单个值
///
/// 查询语句
/// 查询结果(object)
public static object GetSingle(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
{
try
{
connection.Open();
var result = cmd.ExecuteScalar();
return result == DBNull.Value ? null : result;
}
catch (SQLiteException e)
{
throw new Exception("Error executing scalar query.", e);
}
}
}
public static object GetSingle(string sql, params SQLiteParameter[] parameters)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
object result = command.ExecuteScalar();
return result == DBNull.Value ? null : result;
}
}
}
///
/// 执行查询语句,返回DataTable
///
/// 查询语句
/// 查询结果的DataTable
public static DataTable QueryTable(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
DataTable dt = new DataTable();
try
{
connection.Open();
using (SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection))
{
command.Fill(dt);
}
}
catch (SQLiteException ex)
{
throw new Exception("Error executing query.", ex);
}
return dt;
}
}
///
/// 执行查询语句,返回DataSet
///
/// 查询语句
/// 查询结果的DataSet
public static DataSet Query(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
using (SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection))
{
command.Fill(ds);
}
}
catch (SQLiteException ex)
{
throw new Exception("Error executing query.", ex);
}
return ds;
}
}
///
/// 执行查询语句,返回空表格式
///
/// 表名
/// 空表的DataTable
public static DataTable QueryNullTable(string sTableName)
{
string SQLString = $"SELECT * FROM {sTableName} LIMIT 0";
return QueryTable(SQLString);
}
///
/// 执行查询语句,返回SqlDataReader
///
/// 查询语句
/// SqlDataReader
public static SQLiteDataReader ExecuteReader(string strSQL)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
try
{
connection.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SQLiteException e)
{
throw new Exception("Error executing reader.", e);
}
}
//public static SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] parameters)
//{
// SQLiteConnection connection = new SQLiteConnection(connectionString);
// SQLiteCommand command = new SQLiteCommand(sql, connection);
// if (parameters != null)
// {
// command.Parameters.AddRange(parameters);
// }
// return command.ExecuteReader();
//}
public static SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] parameters)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
try
{
// 打开连接
connection.Open();
SQLiteCommand command = new SQLiteCommand(sql, connection);
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
// CommandBehavior.CloseConnection 确保当 reader 被关闭时,连接也会自动关闭
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
// 如果发生异常,确保关闭连接
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
// 重新抛出异常,便于上层捕获
throw;
}
}
public static async Task ExecuteReaderAsync(string sql, params SQLiteParameter[] parameters)
{
// 创建一个 TaskCompletionSource,用于包装同步的 ExecuteReader 方法
return await Task.Run(() =>
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
try
{
// 打开连接
connection.Open();
SQLiteCommand command = new SQLiteCommand(sql, connection);
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
// CommandBehavior.CloseConnection 确保当 reader 被关闭时,连接也会自动关闭
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
// 确保发生异常时关闭连接
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
// 重新抛出异常供上层处理
throw;
}
});
}
///
/// 执行SQL语句清理SQLite数据库的多余空间
///
public static void ClearSQLite()
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand cmd = new SQLiteCommand("VACUUM", connection))
{
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (SQLiteException e)
{
throw new Exception("Error cleaning SQLite database.", e);
}
}
}
// 查询SQLite数据库中的所有表名
public static List GetAllTables()
{
List tableNames = new List();
// 创建数据库连接并打开
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
// SQL查询所有表
string query = "SELECT name FROM sqlite_master WHERE type='table';";
using (SQLiteCommand command = new SQLiteCommand(query, connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// 将表名添加到列表中
tableNames.Add(reader["name"].ToString());
}
}
}
}
return tableNames;
}
//////////////////////////////////////////////////////
}
}