我正在尝试用特定文件夹中的文件名填充PostgreSQL表(psycopg2,Python(。我已经创建了一个功能,应该做的技巧,但我得到了错误:
并非所有参数都在字符串格式化期间转换,
当我运行函数时。我进行了一次测试运行,并以以下方式调用了该函数:
insert_file_names_into_database(["filename1_without_extension", "filename2_without_extension"]),
我没有遇到任何问题,INSERT运行良好。如果我做了以下操作:
insert_file_names_into_database(["filename1.extension", "filename2.extension"]),
然后我得到上面的错误。所以问题似乎是"导致SQL INSERT失败的字符(例如image.jpg(。我试着查阅Psycopg2文档,但没有发现与这个特定案例相关的例子。
我应该如何编辑这段代码,以便即使使用"也能开始工作"文件名中的字符?
def insert_file_names_into_database(file_name_list):
""" insert multiple filenames into the table """
sql = "INSERT INTO mytable(filename) VALUES(%s)"
conn = None
try:
# read database configuration
# connect to the PostgreSQL database
conn = psycopg2.connect(
host="localhost",
database="mydatabase",
user="myusername",
password="mypassword")
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.executemany(sql, file_name_list)
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
我自己已经解决了。我知道在使用INSERT时应该使用元组,但我的函数在不使用"的字符串列表中运行得很好"字符。
我得到的解决方案是将字符串列表转换为元组列表,如下所示:
tuple_file_name = [tuple((file_name,)) for file_name in file_name_list]
例如,如果:
file_name_list = ["filename1.jpg", "filename2.jpg"]
然后将其作为我的函数的输入失败。但通过将其列为元组列表:
tuple_file_name = [tuple((file_name,)) for file_name in file_name_list]
print(tuple_file_name)
[('filename1.jpg',), ('filename2.jpg',)]
现在,函数接受输入tuple_file_name
,文件名保存到SQL表中。