0

I tried to do a shopping cart in the telegram bot using psycopg2 and aiogram, but the data does not appear in the "korzina" column code:

connection.cursor(f'INSERT INTO bot_users(korzina) VALUES({id_tovara}) FROM bot_user WHERE user_id=           {us_id}')
    connection.commit()

Types of columns:

user_id      | bigint 
korzina      | text

I'm using Postgresql.

Nothing happened with the "korzina" column. All data are written correctly (name of columns and table name).

opeonikute
  • 494
  • 1
  • 4
  • 15
  • 1
    **DO NOT** use `f` strings for parameters. Read the docs [Paramter passing](https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries) and follow the instructions. – Adrian Klaver Sep 02 '23 at 15:19

2 Answers2

2

You are calling connection.cursor with a very long name parameter, which is most likely not what you had in mind.

You probably want to create an unnamed cursor object, and then call its execute method:

c = connection.cursor()
c.execute("INSERT INTO blabla ... ")

You may also want to look at the behaviour of connections and cursors when used as context managers.

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
0

The INSERT INTO command does not include the FROM clause, you should instead modify your query to use UPDATE, something like this;

sql_query = "UPDATE bot_users SET korzina = %s WHERE user_id = %s"
cursor.execute(sql_query, (id_tovara, us_id))
connection.commit()