gpt4 book ai didi

python - 通过 python sql 游标使用表名变量

转载 作者:行者123 更新时间:2023-11-29 15:49:27 28 4
gpt4 key购买 nike

我正在使用 python sql 游标动态访问我的数据库,并且我想要使用变量代替表名。到目前为止,我所有的尝试都导致了语法错误,尽管我(认为?)我正在按照预期做事?除非作为变量的表名与作为变量的值不同:

这是我目前拥有的:

cursor.execute("INSERT INTO %s (word=%s,item_id=%s,word_tag=%s,unstemmed_word=%s, word_position=%s, TF=%s, normalized_term_frequency=%s, sentence=%s,anthology_id=%s) "%(table_name, stemmedWord,fle.split()[0], str(word[1]), uniqeWord, word_pos, TF, normalized_term_frequency, sentence, fle.split()[1].split(".")[0]))

我也尝试过这个:

cursor.execute("INSERT INTO %s (word,item_id,word_tag,unstemmed_word, word_position, TF, normalized_term_frequency, sentence,anthology_id) values(%s, %s,%s, %s, %s, %s, %s, %s, %s)",(table_name, stemmedWord,fle.split()[0], str(word[1]), uniqeWord, word_pos, TF, normalized_term_frequency, sentence, fle.split()[1].split(".")[0]))

最佳答案

您不能动态绑定(bind)对象名称,只能动态绑定(bind)值。您必须对表名称进行字符串操作。例如:

sql = "INSERT INTO {} (word=%s,item_id=%s,word_tag=%s,unstemmed_word=%s, word_position=%s, TF=%s, normalized_term_frequency=%s, sentence=%s,anthology_id=%s)".format(table_name)

cursor.execute(sql % (stemmedWord,fle.split()[0], str(word[1]), uniqeWord, word_pos, TF, normalized_term_frequency, sentence, fle.split()[1].split(".")[0]))

关于python - 通过 python sql 游标使用表名变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56847417/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com