如何解决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
我的问题是我该如何重写代码,以免遇到上述错误?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。