Sqlite No transaction is active on this connection

最近使用C#操作sqlite时碰到一个错误,记一下

code = Unknown (-1), message = System.Data.SQLite.SQLiteException (0x80004005): unknown error
No transaction is active on this connection
   在 System.Data.SQLite.SQLiteTransactionBase.IsValid(Boolean throwError)
   在 System.Data.SQLite.SQLiteTransaction.Commit()
   在 wechathelper.UserDBService.updateBatchField(List`1 list_p)
   在 wechathelper.service.IndexManagerService.getRoomListResult(String msg)

分析到的原因是 sqlite的事务自动提交"AutoCommit",值默认是true,一般来说在调用BeginTransaction方法后,这个值会被设置成false,等调用commit方法后会重新设置为true,但是不知道什么影响下,在调用BeginTransaction有几率任然为true,这个时候事务在执行完sql语句的时候就已经提交了,再去调用commit就会产生上述情况。由于sqlite缺少相关状态、设置开启关闭AutoCommit的api,暂时没有找到解决方案。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果您在执行 `ExecuteNonQuery()` 方法时遇到 "No connection associated with this command" 错误,可能是由于连接未正确打开或已关闭导致的。您可以尝试使用以下修改后的代码来解决该问题: ```csharp using System; using System.Data.SQLite; namespace SQLiteExample { class Program { static void Main(string[] args) { string connectionString = "Data Source=your_database_file.db;Version=3;"; using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string tableName = "your_table_name"; string sql = $"PRAGMA table_info({tableName})"; using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string columnName = reader["name"].ToString(); string dropColumnSql = $"ALTER TABLE {tableName} DROP COLUMN {columnName}"; using (SQLiteConnection connection2 = new SQLiteConnection(connectionString)) { connection2.Open(); using (SQLiteCommand dropColumnCommand = new SQLiteCommand(dropColumnSql, connection2)) { dropColumnCommand.ExecuteNonQuery(); } connection2.Close(); } } } } } Console.WriteLine("All columns removed successfully."); Console.ReadLine(); } } } ``` 在此修改后的代码中,我们为每个删除操作创建了一个新的连接,并在执行完操作后手动关闭连接。这样可以确保每个操作都在一个打开的连接上执行,避免了 "No connection associated with this command" 错误。请确保将 `your_database_file.db` 替换为您的SQLite数据库文件的路径和名称,将 `your_table_name` 替换为您要删除列的表名。运行此代码后,它应该能够成功删除指定表的所有列,并输出成功消息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值