开始学习mySQL,并坚持为什么这个命令不起作用。我在UPDATE命令和SELECT *函数之外取得了成功,所以我猜我在调用函数时犯了一个错误,或者%s需要不同...我的google foo没有找到任何东西所以我希望你们都可以帮助我!
非常感谢你寻找!
CODE:
def CheckBalance(UserName, BetAmount): #checks to make sure they can afford the bet. Returns 0 for no 1 for yes
import mysql.connector
cnx = mysql.connector.connect(user='root', password='Password',
host='127.0.0.1',
database='crapsdatabase')
c = cnx.cursor()
BankRoll = c.execute("SELECT PlayerBank FROM player WHERE PlayerName = %s", UserName)
if(BankRoll < BetAmount) or (BetAmount < 0):
c.close()
return 0
if(BankRoll >= BetAmount):
c.close()
return 1
从我们的主程序中导入UpdateDatabase并将其命名为
from plugins.database.UpdateDatabase import UpdateBets
a = UpdateBets.CheckBalance("bob", 100)
print(a)
这会出现以下错误:
C:\python\python.exe C:/Users/Ray/Desktop/bot/plugins/CRAPS/CrapsUpdated.py
Traceback (most recent call last):
File "C:/Users/Ray/Desktop/bot/plugins/CRAPS/CrapsUpdated.py", line 3, in <module>
a = UpdateBets.CheckBalance("bob", 100)
File "C:\Users\Ray\Desktop\bot\plugins\database\UpdateDatabase.py", line 16, in CheckBalance
BankRoll = c.execute("SELECT PlayerBank FROM player WHERE PlayerName = %s", UserName)
File "C:\python\lib\site-packages\mysql\connector\cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\python\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\python\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
答案 0 :(得分:1)
你应该在带有撇号的查询中转义字符串文字,所以它应该是这样的:
c.execute("SELECT PlayerBank FROM player WHERE PlayerName = '%s'", UserName)