Python中的动态INSERT语句

时间:2014-01-15 14:50:55

标签: sql python-2.7 sqlite

我正在努力更新我一直在使用的一些Python代码,并且正在寻找一些关于处理我正在使用的想法的最佳方法的建议。我想改变的代码部分是:

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

代码有效。我的问题是,我可以将“(?,?,?,?)”更改为更像“range()”的动态内容以允许用户输入。我知道我还必须有一个动态创建表语句,所以另一种解决方案可能是计算输入数量。

要更清楚一点:例如,如果我有raw_input(“表包含多少个变量?:”)并且输入为2,程序将知道如何运行(?,?)。 / p>

思想?

(我也使用SQLite3和python 2.7)

3 个答案:

答案 0 :(得分:4)

假设您的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)

答案 1 :(得分:2)

在python3上,使用列表推导和词典我提出了以下简单的代码,它能够基于给定的字典构建Dynamic SQLite插入字符串:

# Data to be inserted:

data = [
  {
    'table': 'customers',
    'values': {
      'name': '"Doctor Who"',
      'email': '"doctorwho@timelords.com"'
    }
  },
  {
    '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(dictionary["values"].keys())  

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

  # 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

答案 2 :(得分:0)

我最近编写了一个函数来快速填充基于表名的表和带有我想插入的行数据的元组列表。我正在使用元组来确定预期的列数:

.jpg