使用Python动态将数据插入SQL数据库

时间:2018-10-18 19:26:30

标签: python sqlite mysql-python

我一直在尝试从一些Python列表中将数据输入数据库:

import sqlite3
db = sqlite3.connect('database.db')
c = db.cursor()
a = ["col1", "col2", "col3"]
b = ["value1", "value2", "value3"]
c.execute("INSERT INTO table_name(?) VALUES (?)", (tuple(a), tuple(b)))
db.commit

但是我总是会收到此错误:

Traceback (most recent call last):
  File "testing.py", line 95, in <module>
    c.execute("INSERT INTO table_name(?) VALUES (?)", (tuple(a), tuple(b)))
sqlite3.OperationalError: near "?": syntax error

我已经尝试过简化事情,并使用循环一次从列表中取出一个项目,并且仅添加这些项目,但这也不起作用。实际上,如果我尝试传递单个变量,我会得到相同的确切错误(例如:

a = "col1"
b = "val1"
c.execute("INSERT INTO table_name(?) VALUES (?)", (a, b))

尽管如此,当我尝试手动传递列名和变量名时,更新的数据库没有任何问题。我想念什么?

1 个答案:

答案 0 :(得分:0)

您不能使用阻止SQL解析器准备查询计划的占位符。这意味着表名和列都不能是占位符。

插入时,您始终可以使用占位符插入所有值。然后,您需要在插入元组中填充适当数量的public static int getValidInt(int greaterThan, Scanner scan) { int input = 0; boolean valid = false; while (!valid) { System.out.println("Enter an integer greater than " + greaterThan + ":"); if (!scan.hasNextInt()) { String garbage = scan.next(); System.out.println(garbage + " is not valid input."); } else { input = scan.nextInt(); if (input <= greaterThan) { System.out.println(input + " is not greater than " + greaterThan); } else { valid = true; } } } return input; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a = getValidInt(1, scan); System.out.println(a); int total = 0; long n = a; while ( n < 1000000 ) { n = n * n; System.out.println(n); total++; } System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ; } 来填充缺失的值:

None

或者,您可以动态建立列名,但保留值的占位符:

b = [None, "value2", None]
c.execute("INSERT INTO table_name (foo, bar, baz) VALUES (?, ?, ?)", (tuple(values)))

只要您确保不允许用户指定列名,或者只要您通过字典对其进行验证,就可以使用此方法。