平板电脑会用到一个下载小说的爬虫软件,它会使用sqlite存放数据。我把数据存放目录选择在内存卡上,过了一年,出现了软件里找不到下载记录的情况,检查了一下目录,发现是数据库文件损坏了。1.3gb大小的数据库文件(主要内容是小说的文本)。我怀疑损坏的主要原因还是内存卡垃圾,是自然的损毁。闪迪256gb的内存卡,售价229元,1gb价格不到1元,可能平板供电也有问题,或者安卓系统的孱弱性,总之我在pc平台没有碰到过这类问题,而且我用dump的方法,把数据提取出来,发现因为错误,只提取了130mb,相比原来的1.3gb,缩水了很多。
在网上搜索,发现主要的解决方法,还是dump出sql语句,然后重新建库。这也提醒我们数据库要做好备份了,网上也搜不到什么别的解决方案了。想想也是,如果官方有方便的方法的话,网上肯定都是类似的回答。
我去官网查了一下,文档fsq里面,有提到
What is an SQLITE_CORRUPT error? What does it mean for the database to be "malformed"? Why am I getting this error?
An SQLITE_CORRUPT error is returned when SQLite detects an error in the structure, format, or other control elements of the database file.
SQLite does not corrupt database files without external help. If your application crashes in the middle of an update, your data is safe. The database is safe even if your OS crashes or takes a power loss. The crash-resistance of SQLite has been extensively studied and tested and is attested by years of real-world experience by billions of users.
That said, there are a number of things that external programs or bugs in your hardware or OS can do to corrupt a database file. See How To Corrupt An SQLite Database File for further information.
You can use PRAGMA integrity_check to do a thorough but time intensive test of the database integrity.
You can use PRAGMA quick_check to do a faster but less thorough test of the database integrity.
Depending how badly your database is corrupted, you may be able to recover some of the data by using the CLI to dump the schema and contents to a file and then recreate. Unfortunately, once humpty-dumpty falls off the wall, it is generally not possible to put him back together again.
官方认为sqlite的安全性还是很不错的,应用程序崩溃不会损坏数据库文件,所以说硬件问题的可能性更大吧,可能就是普通的数据损坏。
01.首先使用 PRAGMA integrity_check;
进行完整性检查
我检查的结果,报了一长串的错误。可见很多内容都损坏了,尤其是我在数据库gui中看到,有一行本该是正数的栏里面的数据都是很大的负数,可见数据确实损坏了。
02.把数据库dump为sql
执行这一步的时候,我dump出来的数据最后一行是ROLLBACK(due to error),注意把这一行改成COMMIT,这样就能抢救一部分数据了。
# 在命令行界面打开旧的数据库
sqlite3 oldfile.db
# 指定输出文件
.output dump.sql
# 执行dump
.dump
03.读取sql到新的数据库
# 创建一个新数据库并打开
sqlite3 newfile.db
# 读取之前创建的sql并执行
.read dump.sql
结果是大部分数据丢失了,但是好在表结构还在,小说列表还完整,关键就是这个列表,我相信这个数据还在,爬虫软件应该能借着重新把小说全部爬出来。