Синтаксическая ошибка в INSERT с использованием psycopg2 - PullRequest
0 голосов
/ 28 марта 2020

Я пытаюсь вставить несколько записей в базу данных POSTGRES с помощью пакета psycopg2.

Я получаю ошибку, которую просто не могу понять.

    import numpy as np
import psycopg2
#video_id, frame_num, human_num, keypoint_id, part_x, part_y, confidence
video_id = [1,1,1]
frame_id = [1,1,1]
human_num = [1,1,1]
keypoint_id = [0,1,2]
part_x = [0.33, 0.33, 0.33]
part_y = [0.66, 0.66, 0.66]
confidence = [0.34, 0.45, 0.67]

recs = np.core.records.fromarrays([video_id, frame_id, human_num,keypoint_id, part_x, part_y, confidence])
a_str = ",".join(map(str, recs))

user = 'XX'
pwd = 'XX'
host = 'XX'
port = 'XX'
database = 'XX'

try:
        connection = psycopg2.connect(user = user,
                                  password = pwd,
                                  host = host,
                                  port = port,
                                  database = database)
        #print ("CONN: Established Connection")
        cursor = connection.cursor()

        # Get the data in the required format
        data_sql =  a_str
        #print ("CONN: Converted to recs")

        # Prepare the INSERT Query  to insert keypoints into pose_data
        records_list_template = ','.join('%s' * len(data_sql))
        #print ("CONN: records_template", records_list_template)
        insert_query = 'INSERT INTO pose_data (video_id, frame_num, human_num, keypoint_id, part_x, part_y, confidence) VALUES %s;'
        print ("CONN: Insert Query is ", insert_query)
        # Execute the query
        #print("CONN: Writing ", data_sql)
        cursor.execute(insert_query, [data_sql])
except (Exception, psycopg2.Error) as error :
        print ("Error in PostgreSQL try block:", error)

finally:
    #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")

У меня есть вывод ниже (содержит ошибку)

('CONN: Вставить запрос is', 'INSERT INTO pose_data (video_id, frame_num, human_num, keypoint_id, part_x, part_y, достоверность) VALUES% s; ') (' Ошибка в PostgreSQL try block: ', ProgrammingError (' синтаксическая ошибка в или около '\' (1, 1, 1, 0, 0.33, 0.66, 0.34) , (1, 1, 1, 1, 0,33, 0,66, 0,45), (1, 1, 1, 2, 0,33, 0,66, 0,67) \ '"\ nLINE 1: ..., keypoint_id, part_x, part_y, доверие ) VALUES \ '(1, 1, 1, ... \ n
^ \ n',))

1 Ответ

0 голосов
/ 28 марта 2020

переменная% s не заменяется ее значением в инструкции

insert_query = 'INSERT INTO pose_data (video_id, frame_num, human_num, keypoint_id, part_x, part_y, confidence) VALUES %s;'

...