Python3:使用多个线程时,sqlite3数据库损坏

问题描述

我有两个同时运行的python线程:1)Thread1打开sqlite数据库,插入数据并关闭sqlite db。 2)Thread2打开sqlite数据库,读取数据并关闭sqlite数据库。

请在下面的其他线程中参考sqlite的实现:

线程1:

try:
    conn = sqlite3.connect('/home/dep/sqliteFile/sqldb_11.db')
    c = conn.cursor()
    query = "CREATE TABLE if not exists department(id integer primary key,timestamp datetime default current_timestamp,dep_id integer not null,dep_name Varchar not null);"
    c.execute(query)
    query = ('INSERT INTO dep (dep_id,dep_name) VALUES (50,'payroll')')
    c.execute(query,row)
    conn.commit()
except Exception as err:
    print(err)
finally:
    c.close()
    conn.close()

线程2:

    #read boolean from a file that indicates whether the sqlite db has been updated today or previous day
    if(!bool_flag): # if sqlite db has not been written today
        while True:
            sqliteConnection = sqlite3.connect('/home/dep/sqliteFile/sqldb_10.db') # sqldb_10.db database was created yesterday in Thread1 instead of sqldb_11.db which is created today
            cursor = sqliteConnection.cursor()
            cursor.execute('''SELECT count(name) FROM sqlite_master WHERE type='table' AND name='dep';''')
            if cursor.fetchone()[0] != 1 : # if sqldb_10 has no table named dep
                print('No table exists')
            else:
                break
    else:
        sqliteConnection = sqlite3.connect('/home/dep/sqliteFile/sqldb_11.db')
        cursor = sqliteConnection.cursor()

    sqlite_select_query = "select id,timestamp,dep_id from dep where `dep_id` > 30 and `dep_id` < 60;"
    cursor.execute(sqlite_select_query)
    records = cursor.fetchall()
    cursor.close()
    sqliteConnection.close()

我遇到的问题是我经常遇到以下sqlite损坏错误:

file is encrypted or is not a database

我使用strace进行调试,以显示数据库已损坏的地方:

18124 read(10,"SQLit",5)              = 5
18124 write(10,"\25\3\3\0\32\2\36)`\365`_#\312\357\305\236\367%\307\255f\34$;\275-\250F\362A",31) = 31

这很可能意味着在sqldb_11.db中写入了垃圾。我了解我的数据库违反了该link

中的2.6节

我的问题是我该如何重写代码,以免遇到上述错误?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...