I’m trying to create a table using psycopg2 and then insert outer data from some jsons. For this reason I defined 2 function: create_words_table() and insert_data():
x
con = psycopg2.connect(
database="dbname",
user="username",
password="password",
host="127.0.0.1",
port="5432"
)
cur = con.cursor()
def create_words_table():
cur.execute(""" CREATE TABLE WORDS
(word_ CHAR(50),
POS_ CHAR(20),
case_ CHAR(20),
animacy_ CHAR(20),
tense_ CHAR(20),
person_ CHAR(20),
number_ CHAR(20),
gender_ CHAR(20),
mood_ CHAR(20),
tonality_ CHAR(20),
POS_score_ REAL NOT NULL,
NEU_score_ REAL NOT NULL,
NEG_score_ REAL NOT NULL );""")
def insert_data(word):
# handle_dict() is a function for getting outer data.
if handle_dict(word) is not None:
(word_from_dict, pos_from_dict, case_from_dict, gender_from_dict,
mood_from_dict, number_from_dict, person_from_dict, tense_from_dict,
tonality_from_dict, pos_score_from_dict, neu_score_from_dict,
neg_score_from_dict) = handle_dict(word)
cur.execute('''INSERT INTO WORDS (word_, POS_, case_, gender_, mood_,
number_, person_, tense_, tonality_, pos_score_, neu_score_, neg_score_)
VALUES (word_from_dict, pos_from_dict, case_from_dict, gender_from_dict,
mood_from_dict, number_from_dict, person_from_dict, tense_from_dict,
tonality_from_dict, pos_score_from_dict, neu_score_from_dict,
neg_score_from_dict)''')
con.commit()
con.close()
So, attempting to execute them:
if __name__ == '__main__':
create_words_table()
logger.info("table created")
insert_data()
logger.info("Records inserted successfully")
I got further error:
Traceback (most recent call last):
File "pathtofile", line 178, in <module>
main()
File "pathtofile", line 172, in main
insert_data()
File "pathtofile", line 148, in insert_data
cur.execute('''
psycopg2.errors.UndefinedColumn: ОШИБКА: столбец "word_from_dict" не существует
# ERROR: column "word_from_dict" does not exist ###
LINE 4: VALUES (word_from_dict, pos_from_dict, case_from_dic
Looking at documentation, I don’t see any mistake applying simple INSERT query and can’t understand why psycopg2 takes a tuple after word VALUE as a table’s fields. If anybody could clear me this, I’ll be very grateful.
Advertisement
Answer
the problem is in your query , you need to change your query to this and pass the tuple as param:
cur.execute('''INSERT INTO WORDS (word_, POS_, case_, gender_, mood_,
number_, person_, tense_, tonality_, pos_score_, neu_score_, neg_score_)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''',handle_dict(word))