pythonpostgresqlflaskpsycopg2werkzeug

SyntaxError: ERROR: INSERT contains more target columns than


i had problem with Insert data from postgresql. API app my code: `

orders = []

@app.route('/client/order', methods=["POST", "OPTIONS"])
async def save_order(request):
    conn = psycopg2.connect(user='postgres', password='*********', database='pyDB', host='127.0.0.1', port=5432)
    cursor = conn.cursor()
    if request.method == "POST":
        order = request.json.get('clientId,drinkId,status,time')
        orders.append(order)
        insert = sql.SQL('INSERT INTO orders (client_id,drink_id,status,order_time) VALUES ({})').format(sql.SQL(', ').join(map(sql.Literal,orders)))
        cursor.execute(insert)
        conn.commit()
        return response.json({"order": "saved"})
    else:
        return response.json({})`

when i parsing json:

`{
"clientId":"1",
"drinkId":"5",
"status":"false",
"time":"20232410 10:15:45"
}`

i had this problem:

 psycopg2.errors.SyntaxError: ERROR: INSERT contains more target columns than expressions LINE 1: INSERT INTO orders (client_id,drink_id,status,order_time) VALUES...

and this is my table:

create table orders(
int drink_id not null,
int client_id not null,
boolean status not null,
timestamp without zone order_time
)

i tried change massive orders, tried change sql request but anything doesnt work PLs help


Solution

  • Just spell out the fields you get from your data:

    order = request.json
    cursor.execute(
        "INSERT INTO orders (client_id,drink_id,status,order_time) VALUES (%s,%s,%s,%s)",
        (
            order["clientId"],
            order["drinkId"],
            order["status"],
            order["time"],
        ),
    )
    conn.commit()