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
?
JavaScript
x
27
27
1
import random
2
import mysql.connector
3
4
while True:
5
letters = "AB"
6
let = random.choice(letters)
7
print(let)
8
human = input("Human : ")
9
db = mysql.connector.connect(host = 'localhost',
10
user = 'root',
11
password = '',
12
database = 'test')
13
mycs = db.cursor()
14
15
16
mycs.execute(" SELECT * FROM human WHERE {} = {}".format(let,human))
17
18
19
data = mycs.fetchall()
20
21
if data:
22
print("Name exists")
23
else:
24
print("Name does not exist")
25
26
mycs.close()
27
The error:
JavaScript
1
15
15
1
B
2
3
Human : brad
4
5
Traceback (most recent call last):
6
File "C:UsersAdministratorDesktopt.py", line 16, in <module>
7
mycs.execute(" SELECT * FROM human WHERE {} = {}".format(let,human))
8
File "C:Program FilesPython39libsite-packagesmysqlconnectorcursor.py", line 568, in execute
9
self._handle_result(self._connection.cmd_query(stmt))
10
File "C:Program FilesPython39libsite-packagesmysqlconnectorconnection.py", line 686, in cmd_query
11
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
12
File "C:Program FilesPython39libsite-packagesmysqlconnectorconnection.py", line 573, in _handle_result
13
raise errors.get_exception(packet)
14
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'brad' in 'where clause'
15
Advertisement
Answer
You just need to put the constant in the to the query between single quotes:
JavaScript
1
2
1
(" SELECT * FROM human WHERE {} = '{}'".format(let,human))
2