Using a variable for a table name with python sql cursor

后端 未结 2 1774
天命终不由人
天命终不由人 2021-01-25 15:57

I am using python sql cursor to dynamically access my database and I am in a situation where I want to use a variable in place of a table name. So far all of my attempts have r

相关标签:
2条回答
  • 2021-01-25 16:21

    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.

    0 讨论(0)
  • 2021-01-25 16:32

    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]))
    
    0 讨论(0)
提交回复
热议问题