2014-01-15 69 views
5

我正致力於更新一些我一直在使用的Python代碼,並且正在尋找一些處理我正在處理的想法的最佳方式的建議。我想要更改的部分代碼是:Python中的動態INSERT語句

my_reader = csv.reader(input, delimiter = ',',quotechar='|') 
mouse.executemany("INSERT INTO Example_Input (ID,Name,Job,Salary) VALUES (?,?,?,?)", my_reader) 

該代碼有效。我的問題是,我可以將「(?,?,?,?)」更改爲更加動態的內容,例如「range()」以允許用戶輸入。我知道我也必須有一個動態的create table語句,所以另一個解決方案可能是計算輸入的數量。例如,如果我有raw_input(「表中包含多少個變量?:」)並且輸入爲2,程序就會知道它運行得像if(?,?)那樣。

想法?

(還我使用的SQLite3和Python 2.7)

回答

2

假設您CSV有一個報頭字段,你可以使用一個DictReader和產生的字段名和參數及其fieldnames財產。

DictReader的構造函數允許您指定字段名稱,如果它們不在文件中,那麼您可以根據需要詢問用戶該信息。

假設頭是在文件中,這個例子代碼應工作:

import csv 
import sqlite3 

#Give the table a name and use it for the file as well 
table_name = 'Example' 
a = open(table_name + '.csv', 'r') 

#Use a dict reader 
my_reader = csv.DictReader(a) 
print my_reader.fieldnames # Use this to create table and get number of field values,etc. 

# create statement 
create_sql = 'CREATE TABLE ' + table_name + '(' + ','.join(my_reader.fieldnames) + ')' 
print create_sql 

#open the db 
conn = sqlite3.connect('example.db') 
c = conn.cursor() 
# Create table using field names 
c.execute(create_sql) 
insert_sql = 'insert into ' + table_name + ' (' + ','.join(my_reader.fieldnames) + ') VALUES (' + ','.join(['?'] * len(my_reader.fieldnames))+ ')' 
print insert_sql 

values = [] 
for row in my_reader: 
    row_values = [] 
    for field in my_reader.fieldnames: 
     row_values.append(row[field]) 
    values.append(row_values) 

c.executemany(insert_sql, values) 
+0

我知道一些CSV文件中沒有包含變量名頭......然而,這是肯定的東西,我會考慮,只是狀態在'raw_input()'中e程序將假定文檔包含這些標題。 – DataforDays

0

我最近寫了一個函數來快速填充基於表名和表元組與行的數據列表,我想要插入。我使用的元組,以確定預期多少列:

def populate_table(table_name, data): 
    #Grab first tuple and find out how many columns are expected to be edited 
    num_columns = len(data[0]) 
    try: 
     cursor.executemany("INSERT INTO {} VALUES({})".format(table_name, ','.join(['?' for s in xrange(num_columns)]), data) 
     conn.commit() 
    except sqlite3.OperationalError: 
     ... 
1

在python3,使用列表內涵和詞典我想出了以下簡單的代碼,可以構建基於給定一個動態的SQLite插入串詞典:

# Data to be inserted: 

data = [ 
    { 
    'table': 'customers', 
    'values': { 
     'name': '"Doctor Who"', 
     'email': '"[email protected]"' 
    } 
    }, 
    { 
    'table': 'orders', 
    'values': { 
     'customer_id': '1', 
     'item': '"Sonic Screwdriver"', 
     'price': '1000.00' 
    } 
    } 
] 


def generate_insert_query(dictionary): 
    table = dictionary["table"] # Get name of the table 

    # Get all "keys" inside "values" key of dictionary (column names) 
    columns = ', '.join([key for key, value in dictionary["values"].items()]) 

    # Get all "values" inside "values" key of dictionary (insert values) 
    values = ', '.join([value for key, value in dictionary["values"].items()]) 

    # Generate INSERT query 
    print(f"INSERT INTO {table} ({columns}) VALUES ({values})" + "\n") 


# Generate QUERY for each dictionary inside data list 
for query in data: 
    generate_insert_query(query) 

嘗試在代碼:https://repl.it/KNZg/2