How to pass python variable to sql query?

Asked

Viewed 581 times

-2

I am using Mysql as a database. I wanted to be able to pass the value of a python variable as a parameter in this query.

Ex:

cursor = connection.cursor()

variavel_nome_cliente = input('Digite aqui o nome do cliente: ')

query = ('INSERT INTO tabela_ficticia(coluna_nomes) VALUES (variavel_nome_cliente)')

cursor.execute(query)

I’ve tried it anyway, but I’m not able to take the value that is inside the python variable and pass it in the query I do in SQL.

2 answers

0

You can use Python fstrings and concatenate the variable in the query string

query = (f'INSERT INTO tabela_ficticia(coluna_nomes) VALUES ({variavel_nome_cliente})')

Note that the variable is between keys { } and has a f before the quotation marks

Source: https://www.python.org/dev/peps/pep-0498

  • I think I got it. I did so: variavel_client name = input('Type here the client name: ') query = ('INSERT INTO fictitious table(column_names) VALUES ({})'). format(variable_client name) cursor.execute(query)

  • In this case it does the same thing I wrote in the reply. The font link contains a comparison of the format and f-strings (https://www.python.org/dev/peps/pep-0498/#Differences-between-f-string-and-str-format-Expressions). In my opinion it would be easier to understand the query if the f-strings were used

0

I think I did it. I did it like this:

variavel_nome_cliente = input('Digite aqui o nome do cliente: ') 

query = ('INSERT INTO tabela_ficticia(coluna_nomes) VALUES ({})').format(variavel_nome_cliente) 

cursor.execute(query)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.