Python code complete array of the flash memory sqlite database (including code)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/iCloudEnd/article/details/100191151

The following code can be directly used to store array data in the database

The first step in preparing the data

  • The following definition of a name
    para_name = [ 'mkey', ' uni_int', 'pinyin']
  • Providing at the data
    para_list = [( 'in', '20013', 'zhong '), ( ' country', '22269', 'zhong ')]

Storing data into the database sqlite

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

The complete code

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

Guess you like

Origin blog.csdn.net/iCloudEnd/article/details/100191151