将sqlite查询结果导入到文本文件

下班前接到一个需求,要将sqlite数据库中的某个字段导出保存到一个文本中,数据大概有1000w左右,于是我就写了一个python脚本,来做这个事情。

#!/usr/xxx/bin/python

import os,sys
import sqlite3
import logging

sys.path.append('.')
# logger configure
logger = logging.getLogger()
handler = logging.FileHandler('/home/admin/tmp/xxx.txt')
logger.addHandler(handler)
logger.setLevel(logging.NOTSET)

sqlfile_path = '/home/admin/tmp/user.sql'

def write_to_file(guid):
    total_count = get_total_count(guid)
    page_size = 10000
    offset_num = 0
	op_num = 0
    while op_num < total_count:
        array_list = get_data([guid,page_size,op_num])
        offset_num = offset_num + 1
        op_num = offset_num * page_size
	for n in array_list:
            logger.info(n)

def get_total_count(guid):
    conn = sqlite3.connect(sqlfile_path)
    cur = conn.cursor()
    cur.execute('select count(*) from table_name where id = \'' + guid + '\'')
    try:
        count = cur.fetchone()[0]
    except:
        count = 0
    cur.close()
    conn.close()
    return count

def get_data(item):
    conn = sqlite3.connect(sqlfile_path)
    cur = conn.cursor()
    cur.execute('select name from table_name where id = \'' + item[0] + '\' limit ' + item[1] + ' offset ' + item[2])
    array_list = []
    for r in cur.fetchall():
        array_list.append(r[0])
    cur.close()
    conn.close()
    return array_list
	
if '__maiin__' == __name__:
    for guid in ['123456789','987654321']:
        write_to_file(guid)
考虑到数据还是有一点大的,所以就每次查询10000条操作,写完后运行起来,然后我就下班走人了,第二天上班发现这个脚本居然还在跑着,一晚上还没有结束。那叫一个头疼啊。。。 这不是 GC 。

既然这么慢,那我就慢慢等吧,然后开始做其他事情去了,GC来了,兄弟我在测试其他程序的时候,一个不小心,在运行脚本的时候,把python脚本跑出来的文本给删了,连python脚本也一起全删了,当我意识过来的时候,泪流满面啊。。。

就在我沮丧的时候,旁边一同学问了我情况,然后的给了我一行代码

sqlite3 user.sql "select name from table_name where id = '123456789'" >> xxx.txt

之后十分钟,数据全导出来了,效率真TM高。

PS:

python脚本可以用多线程处理,能提高效率,由于时间短,我就没去做,而且兄弟我对pyton也不是很熟悉

希望高人多多指点,有任何可以改进的地方,多多给小弟我指点吧,拍砖的也热烈欢迎。

共同提高,谢谢

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能