在python SQL游标中为表名使用变量

时间:2018-06-25 07:47:07

标签: python sql python-cursor

我正在使用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]))

2 个答案:

答案 0 :(得分:2)

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

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]))

答案 1 :(得分:1)

如果您使用的是python> = 3.6,则可能会更好:

 cursor.execute(f'INSERT INTO {table_name} (word="{stemmedWord}",item_id={fle.split()[0]},word_tag={str(word[1])},unstemmed_word="{oword_posrmuniqeWord}", word_position=word_pos, TF={TF}, normalized_term_frequency={normalized_term_frequency}, sentence="{sentence}",anthology_id={fle.split()[1].split(".")[0])}' 

但是我认为您的语法错误来自两件事:

  1. 您提供了一个字符串以拆分文件。 (更正后,默认为空格-可以!)

  2. 您没有在sql字段中引用似乎是显而易见的字符串。