Using a variable for a table name with python sql cursor

£可爱£侵袭症+ 提交于 2019-12-02 02:47:31

You cannot dynamically bind object names, only values. You'll have to resort to string manipulation for the table's name. E.g.:

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

If you are on python >= 3.6 this is probably better:

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

but I think your syntax errors are coming from two things:

  1. you have provided a string to split fle on. (Correction this defaults to space - so is OK!)

  2. you haven't quoted what seem to be obvious strings in you sql fields.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!