解包多个值并存储到数据库失败

2024-04-20 04:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,我是calling insert_into_db_tmp()。但是,当我执行它时,它使用的是完整表示,而不是test.com/test2path的值

calling insert_into_db_tmp()声明如下所示:

def insert_into_db_tmp(dbcursor, table, col, val):
    try:
        query = "INSERT INTO %s (%s) VALUES (%s)",(table, ",".join(col), ",".join(val))
        print(query)
        dbcursor.execute(query)
        print("inserted!")
    except pymysql.Error as exc:
        print("error inserting...\n {}".format(exc))

我这样称呼:

connection=conn_db()
table = ['test']
col = ['path',]
val = ['test.com/test2',]
insert_into_db_tmp(connection, settings.dni+table,str(col),str(val))

当我执行这个时,我得到:

INSERT INTO test () VALUES ('{'vals': ['test.com/test2'], 'cols': ['path']}')
error inserting...
 (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'vals': ['test.com/test2'], 'cols': ['path']}')' at line 1")

注意:insert_into_db_tmp()的目标是允许输入多个col,以及多个val。所以它们在未来可能会是这样的:

cols=['path','address']
vals=['somesite.com/id=6', '123 Hector Lane']

有人能帮我解决这个问题吗

谢谢你


Tags: pathtestcomdbtablecolerrorval