简体   繁体   English

从函数** keywords为sql语句创建一个字符串

[英]Create a string for sql statement from function **keywords

I have a csv file 'users.csv' that looks like this: 我有一个csv文件“ users.csv”,如下所示:

AppID,Perm,LastLogon,Email,FirstName
jimmeny1,admin,today,jim5@zerlina.com,pop1
jimmeny2,admin,today,jim10@zerlina.com,pop2
jimmeny3,admin,today,jim6@zerlina.com,pop3

I created the below function to load any number of columns from a csv into a sqlite table: 我创建了以下函数,将csv中的任意数量的列加载到sqlite表中:

import sqlite3, csv

def bulkload(file, **args):
    sqlite = sqlite3.connect('mydb.db')
    s1 = sqlite.cursor()
    cols_string = '('
    cols = []
    for i in args.iteritems():
        col = '{} {}'.format(i[0], i[1][1])
        cols.append(col)
    for x, i in enumerate(cols):
        if x != len(cols) - 1:
            cols_string += i + ','
        if x == len(cols) - 1:
            cols_string += i + ')'
    sql1 = "CREATE TABLE IF NOT EXISTS mytable {}".format(cols_string)
    s1.execute(sql1)

An example call to the function: 该函数的示例调用:

bulkload('users.csv', appid=(0, 'text'), perm=(1,'text'), email=(3,'text'))

Is there an easier or more elegant or simply more pythonic way to create the string 'cols_string' that declares the column names and storage classes? 有没有更简单或更优雅或更简单的Python方式创建声明列名称和存储类的字符串'cols_string'?

You should replace the following 您应该替换以下内容

cols_string = '('
for x, i in enumerate(cols):
    if x != len(cols) - 1:
        cols_string += i + ','
    if x == len(cols) - 1:
        cols_string += i + ')'

with the following, which is more pythonic & faster too (due to ''.join() method) 与以下,这是更多的pythonic&更快(由于''.join()方法)

cols_string = '(' + ','.join(cols) + ')'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM