Python代码大全之数组快速存储到sqlite数据库(含代码)

下面代码可以直接用于将数组数据存储到数据库中

第一步准备数据

  • 定义一下列名称
    para_name=[‘mkey’,‘uni_int’,‘pinyin’]
  • 提供一下数据
    para_list=[(‘中’,‘20013’,‘zhong’),(‘国’,‘22269’,‘zhong’)]

将数据存储到sqlite数据库中

dbname=‘pypinyin.db’
tname=‘pypinyin_dict’
para2db(dbname,tname,para_name,para_list)

完整代码

import sqlite3
import os

'''
from pinyin2db import *
para_name=['mkey','uni_int','pinyin']
para_list=[('中','20013','zhong'),('国','22269','zhong')]
dbname='pypinyin.db'
tname='pypinyin_dict'
para2db(dbname,tname,para_name,para_list)
'''



def para2db(dbname,tname,para_name,para_list,need_remove=False):
	# 通常可以关闭,不删除
	if need_remove:createdb(dbname)
	droptable(dbname,tname)
	createtable(dbname,tname,para_name)
	save2db(dbname,tname,para_name,para_list)

# 数据库如果存在就删除
def createdb(dbname):
	if os.path.isfile(dbname):os.remove(dbname)
	import sqlite3
	conn = sqlite3.connect(dbname)
	conn.close()
	return 

# 删除表格
def droptable(dbname,tname):
    conn = sqlite3.connect(dbname)
    c = conn.cursor()
    
    c.execute('''DROP TABLE IF EXISTS ''' +tname)
    conn.commit()
    conn.close()
    return 'ok'

# 创建表格
def createtable(dbname,tname,para_name):
    conn = sqlite3.connect(dbname)
    c = conn.cursor()
    paraStr,vstr,cstr=getParaStr(para_name)
    c.execute('CREATE TABLE ' +tname+' (ID INTEGER PRIMARY KEY  AUTOINCREMENT,'+cstr+');')
       
    conn.commit()
    conn.close()
    return 'ok'

#保存到数据库
def save2db(dbname,tname,para_name,para_list):
	conn = sqlite3.connect(dbname)
	c = conn.cursor()
	paraStr,vstr,cstr=getParaStr(para_name)
	for item in para_list: 
		msql='INSERT INTO '+tname+' ('+paraStr+') VALUES ('+ vstr+')'
		para=item
		#print(msql)
		#print(para)
		c.execute(msql,para)
        
	conn.commit()
	conn.close()
	return 


#------------
#辅助
#-----------
'''
para_name=['mkey','uni_int','pinyin']
getParaStr(para_name)
 ('mkey,uni_int,pinyin', '?,?,?', 'mkey TEXT,uni_int TEXT,pinyin TEXT ')

rs: 列名称,wh:列问号,cstr: 列属性
'''
def getParaStr(mcol_list):
	rs=''
	wh=''
	cstr=''
	for item in mcol_list:
		if item == mcol_list[-1]:
			rs=rs+item
			wh=wh+'?'
			cstr=cstr+item+' TEXT '
		else:
			rs=rs+item+','
			wh=wh+'?,'
			cstr=cstr+item+' TEXT,'
	return rs,wh,cstr

你可能感兴趣的:(python,sqlite)