-2

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

1
  • i find way how i can do it Commented Oct 24, 2023 at 8:40

1 Answer 1

0

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.