將sqlite查詢結果導入到文本文件

下班前接到一個需求,要將sqlite數據庫中的某個字段導出保存到一個文本中,數據大概有1000w左右,因而我就寫了一個python腳本,來作這個事情。 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腳本也一塊兒全刪了,當我意識過來的時候,淚流滿面啊。。。 sql

就在我沮喪的時候,旁邊一同窗問了我狀況,而後默默的給了我一行代碼: shell

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

以後十分鐘,數據全導出來了,效率真TM高。 數據庫

PS: 多線程

python腳本能夠用多線程處理,能提升效率,因爲時間短,我就沒去作,並且兄弟我對pyton也不是很熟悉 app

但願高人多多指點,有任何能夠改進的地方,多多給小弟我指點吧,拍磚的也熱烈歡迎。 測試

共同提升,謝謝 fetch

相關文章
相關標籤/搜索