修复 Sqlite "database disk image is malformed"

发布时间 2023-06-15 10:36:34作者: 物华天宝之藏

Sqlite 是用于移动设备的轻量级数据库。Android 编译遇到出错异常:

database disk image is malformed

 

处理方法为通过对 sqlite 提供的修复命令建立脚本封装自动处理。修复方法来自网络搜索,年代久远,出处不可考,如找到出处,本文引用改为链接。

 

 1 #1.dumpSQL语句
 2 def __dumpSql(self):
 3         cmd = "cd "+self.__path+"&"+self.__path[0:2]+"&"+'''\
 4         sqlite3.exe {oldFile}<dump.sql'''.format(oldFile = self.__oldFile)
 5         os.system(cmd)
 6 
 7 
 8 #这里的dump.sql里面就是
 9 #.output tmp.sql
10 #.dump
11 #.quit
12 
13 
14 #2.修改临时文件的最后一行
15 def __modLastLine(self):
16         with open(self.__tmpFilePath,"rb+") as f:
17             # 获取文件大小
18             fsize = os.path.getsize(self.__tmpFilePath)
19             # 设置初始偏移量
20             offset = -8
21         
22             while -1*offset <fsize:
23                 # 从后往前定位
24                 f.seek(offset ,os.SEEK_END)
25                 # 读取当前行记录
26                 lines = f.readlines()
27                 # 如果当前的行数已经大于等于2了,说明最后一行的所有字符已经包括读取完了
28                 if len(lines) >=2:
29                     # 获取最后一行的字符长度
30                     last_line_len = len(lines[-1])
31                     # 重新seek之后,用truncate()函数进行截取
32                     f.seek(-last_line_len,os.SEEK_END)
33                     f.truncate()
34                     # 在最后再加上Commit;
35                     f.write(b"Commit;")
36                     return
37                 else:
38                     offset*=2
39 
40 
41 #3.读取临时文件,并写新库
42 def __readSql(self):
43        cmd = "cd "+self.__path+"&"+self.__path[0:2]+"&"+'''\
44        sqlite3.exe {newFile}<read.sql'''.format(newFile = self.__newFile)
45        os.system(cmd)
46 
47 
48 #此处read.sql内容:
49 #.read tmp.sql
50 #.quit
51 
52 
53 #4.修复完成后删除临时文件
54 def __delTmp(self):
55        cmd = "cd "+self.__path+"&"+self.__path[0:2]+"&"+'''\
56        del {tmpFile}'''.format(tmpFile=self.__tmpFile)
57        os.system(cmd)

 

2023/6 整理