I wrote a simple script that shows the user a letter and he has to write a human name that starts with the same letter, but I am having a problem automatically compensating for the column name using a variable… Is there a suggestion?
How do I replace the column name with the variable let?
import random
import mysql.connector
while True:
letters = "AB"
let = random.choice(letters)
print(let)
human = input("Human : ")
db = mysql.connector.connect(host = 'localhost',
user = 'root',
password = '',
database = 'test')
mycs = db.cursor()
mycs.execute(" SELECT * FROM human WHERE {} = {}".format(let,human))
data = mycs.fetchall()
if data:
print("Name exists")
else:
print("Name does not exist")
mycs.close()
The error:
B
Human : brad
Traceback (most recent call last):
File "C:UsersAdministratorDesktopt.py", line 16, in <module>
mycs.execute(" SELECT * FROM human WHERE {} = {}".format(let,human))
File "C:Program FilesPython39libsite-packagesmysqlconnectorcursor.py", line 568, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:Program FilesPython39libsite-packagesmysqlconnectorconnection.py", line 686, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:Program FilesPython39libsite-packagesmysqlconnectorconnection.py", line 573, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'brad' in 'where clause'
Advertisement
Answer
You just need to put the constant in the to the query between single quotes:
(" SELECT * FROM human WHERE {} = '{}'".format(let,human))