123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461 |
- 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;";
- /// <summary>
- /// 获取连接字符串
- /// </summary>
- public static string GetConnStr()
- {
- return connectionString;
- }
- /// <summary>
- /// 创建本地库连接
- /// </summary>
- /// <returns>返回本地库连接</returns>
- 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();
- }
- }
- /// <summary>
- /// 执行查询语句,返回一个值
- /// </summary>
- /// <param name="SQLString">SQL语句</param>
- /// <returns>返回的值</returns>
- 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);
- }
- }
- }
- /// <summary>
- /// 执行SQL语句,返回影响的记录数
- /// </summary>
- /// <param name="SQLString">SQL语句</param>
- /// <returns>影响的记录数</returns>
- 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);
- }
- }
- }
- /// <summary>
- /// 执行一组SQL语句
- /// </summary>
- /// <param name="SQLList">SQL语句集合</param>
- /// <returns>成功返回True,失败返回False</returns>
- public static bool ExecuteSql(List<string> 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);
- }
- }
- }
- }
- /// <summary>
- /// 执行SQL语句,带参数
- /// </summary>
- /// <param name="SQLString">SQL语句</param>
- /// <param name="cmdParms">SQL参数</param>
- /// <returns>影响的记录数</returns>
- 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);
- }
- }
- }
- /// <summary>
- /// 删除指定表的所有数据
- /// </summary>
- /// <param name="TableName">指定的表名</param>
- /// <returns>影响的记录数</returns>
- public static int DelTableData(string TableName)
- {
- string SQLString = $"DELETE FROM '{TableName}'";
- return ExecuteSql(SQLString);
- }
- /// <summary>
- /// 执行查询语句,返回单个值
- /// </summary>
- /// <param name="SQLString">查询语句</param>
- /// <returns>查询结果(object)</returns>
- 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;
- }
- }
- }
- /// <summary>
- /// 执行查询语句,返回DataTable
- /// </summary>
- /// <param name="SQLString">查询语句</param>
- /// <returns>查询结果的DataTable</returns>
- 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;
- }
- }
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- /// <param name="SQLString">查询语句</param>
- /// <returns>查询结果的DataSet</returns>
- 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;
- }
- }
- /// <summary>
- /// 执行查询语句,返回空表格式
- /// </summary>
- /// <param name="sTableName">表名</param>
- /// <returns>空表的DataTable</returns>
- public static DataTable QueryNullTable(string sTableName)
- {
- string SQLString = $"SELECT * FROM {sTableName} LIMIT 0";
- return QueryTable(SQLString);
- }
- /// <summary>
- /// 执行查询语句,返回SqlDataReader
- /// </summary>
- /// <param name="strSQL">查询语句</param>
- /// <returns>SqlDataReader</returns>
- 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<SQLiteDataReader> 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;
- }
- });
- }
- /// <summary>
- /// 执行SQL语句清理SQLite数据库的多余空间
- /// </summary>
- 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<string> GetAllTables()
- {
- List<string> tableNames = new List<string>();
- // 创建数据库连接并打开
- 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;
- }
- //////////////////////////////////////////////////////
- }
- }
|