Python executemany 函数的语法错误
Python syntax error for executemany function
我正在尝试使用 python 将数据插入我的数据库,但我的查询中存在语法错误。我试图让代码获取一个列表,并能够将列表添加到 postgresql table 的一行中。我已经查找了一些将列表添加到 table 中的方法,其中一些方法带有“?”在里面。我不知道这是什么意思,也不知道为什么会导致错误。它给我的错误是:
syntax error at or near ","
LINE 1: INSERT INTO TestTable VALUES (?, ?, ?, ?, ?, ?, ?);
这是我的代码。
var_string = ', '.join('?' * len(items_list))
query_string = 'INSERT INTO TestTable VALUES (%s);' % var_string
cur.executemany(query_string, items_list)
PyGreSQL 的参数按格式、名称或位置描述:
query_string = 'INSERT INTO TestTable VALUES (%(id)d, %(name)s, %(date)s)'
cur.execute(query_string, dict(
id = 1, name = 'Cap Lee', date = datetime.date.today()))
或
query_string = 'INSERT INTO TestTable VALUES (%d, %s, %s)'
cur.execute(query_string, (1, 'Cap Lee', datetime.date.today()))
好的,我找到了问题的答案。所以我能够找到另一种方法来将列表添加到我的 table。我首先对查询进行了硬编码,然后我了解到“?”标记用于另一个框架,而不是 postgresql。对于 postgresql,我需要使用 %s。我用“%s”字符替换了问号,它起作用了。接下来我做的是修复一个不那么硬编码的版本。这是:
items = [data] // items is the list we are trying to add to the db table
copy_string = re.sub(r'([a-z])(?!$)', r',', '%s' * len(items)) // len of items list is 7
final_string = re.sub(r'(?<=[.,])(?=[^\s])', r' ', copy_string)
query_string = 'INSERT INTO TestTable VALUES (%s);' % final_string
cur.execute(query_string, items)
查询字符串的输出应如下所示:
INSERT INTO TestTable VALUES(%s, %s, %s, %s, %s, %s, %s);
每个“%s”字符从列表中获取一个值。该代码接受一个列表并将它们添加到数据库中的一行中 table.
我正在尝试使用 python 将数据插入我的数据库,但我的查询中存在语法错误。我试图让代码获取一个列表,并能够将列表添加到 postgresql table 的一行中。我已经查找了一些将列表添加到 table 中的方法,其中一些方法带有“?”在里面。我不知道这是什么意思,也不知道为什么会导致错误。它给我的错误是:
syntax error at or near ","
LINE 1: INSERT INTO TestTable VALUES (?, ?, ?, ?, ?, ?, ?);
这是我的代码。
var_string = ', '.join('?' * len(items_list))
query_string = 'INSERT INTO TestTable VALUES (%s);' % var_string
cur.executemany(query_string, items_list)
PyGreSQL 的参数按格式、名称或位置描述:
query_string = 'INSERT INTO TestTable VALUES (%(id)d, %(name)s, %(date)s)'
cur.execute(query_string, dict(
id = 1, name = 'Cap Lee', date = datetime.date.today()))
或
query_string = 'INSERT INTO TestTable VALUES (%d, %s, %s)'
cur.execute(query_string, (1, 'Cap Lee', datetime.date.today()))
好的,我找到了问题的答案。所以我能够找到另一种方法来将列表添加到我的 table。我首先对查询进行了硬编码,然后我了解到“?”标记用于另一个框架,而不是 postgresql。对于 postgresql,我需要使用 %s。我用“%s”字符替换了问号,它起作用了。接下来我做的是修复一个不那么硬编码的版本。这是:
items = [data] // items is the list we are trying to add to the db table
copy_string = re.sub(r'([a-z])(?!$)', r',', '%s' * len(items)) // len of items list is 7
final_string = re.sub(r'(?<=[.,])(?=[^\s])', r' ', copy_string)
query_string = 'INSERT INTO TestTable VALUES (%s);' % final_string
cur.execute(query_string, items)
查询字符串的输出应如下所示:
INSERT INTO TestTable VALUES(%s, %s, %s, %s, %s, %s, %s);
每个“%s”字符从列表中获取一个值。该代码接受一个列表并将它们添加到数据库中的一行中 table.