2013-11-15 38 views
1

我有一個看起來像這樣的csv文件「users.csv」:從函數用於創建SQL語句的字符串**關鍵字

AppID,Perm,LastLogon,Email,FirstName 
jimmeny1,admin,today,[email protected],pop1 
jimmeny2,admin,today,[email protected],pop2 
jimmeny3,admin,today,[email protected],pop3 

我創建了以下功能從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) 

一個例子調用該函數:

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

是否有一個更容易或更ELE gant或者更簡單的pythonic方法來創建聲明列名稱和存儲類的字符串'cols_string'?

回答

1

此時應更換以下

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

與以下,這是更Python &也更快(因爲 ''。加入()方法)

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

這是偉大的,感謝@阿希什。如果沒有人能夠更好地回覆我,我會在今天剩下的時間裏留下問題,我會將你的回答標記爲正確的。 –