0

I am encountering a problem while updating a table. The code is from telegram bot. We are receiving messages from user, and asking him for a name. This is the variable 'first_name'. We already know his user_id which is integer. Then I am trying to do

def bd_set(body):
    cursor.execute(body)
    connect.commit()

bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},{first_name})")

and getting an error: no such column "John".

But if I try without variable, the code works:

bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'John')")

So, I cannot input varibale (first_name), while variable'user_id' inputs easily.

what can solve the issue?

1
  • OP, I strongly urge you to use the parameterized version of the query I show in my answer instead of the one you have accepted. SQL injection is very serious. Commented Feb 28, 2022 at 12:46

2 Answers 2

1

The code in the question and in both existing answers has the same major problem: they are wide open to a serious security vulnerability called SQL injection.

Don't build SQL queries by sticking strings together.

Instead, pass the parameters to cursor.execute() separately:

def bd_set(body, parameters=None):
    cursor.execute(body, parameters)
    connect.commit()

bd_set(
    f"INSERT INTO user_info (user_id, first_name) VALUES(%s, %s)",
    (user_id, first_name),
)

I replaced the placeholders here with %s but depending on your database driver you might have to use different syntax.

Sign up to request clarification or add additional context in comments.

Comments

0

You have a problem with quotation marks. As first_name is a string, and as you are using f string, you need to use quotation marks

bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'{first_name}')")

You should try to use prepared statements to avoid this kind of problems and to avoid sql injection

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.