如何使用参数将整数值提取到带有 Python 连接器的 MySQL 数据库中
How to fetch integer values using parameters into a MySQL database with Python connector
我正在尝试使用 python 连接器从 MySQL 数据库中获取数据。我想获取匹配 ID
的记录。 ID 具有整数数据类型。这是代码:
custID = int(input("Customer ID: "))
executeStr = "SELECT * FROM testrec WHERE ID=%d"
cursor.execute(executeStr, custID)
custData = cursor.fetchall()
if bool(custData):
pass
else:
print("Wrong Id")
但是代码引发了一个错误:
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 '%d' at line 1
知道为什么整数占位符 %d
会产生这个吗?
字符串只接受 %s 或 %(name)s ,不接受 %d。
executeStr = "SELECT * FROM testrec WHERE ID=%s"
并且变量应该在一个元组中,尽管这会因您使用的版本而异,您可能需要使用:
cursor.execute(executeStr, (custID,))
这里有更多信息https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
current version支持的变量类型有:int
,long
,float
,string
,unicode
,bytes
,bytearray
,bool
,none
,datetime.datetime
,datetime.date
,datetime.time
,time.struct_time
,datetime.timedelta
,和 decimal.Decimal
您应该尝试 %s 而不是 %d。这是因为你的 MYSQL 的数据类型可能是 int 但你应该传递给 cursor 的参数必须是 string.
试试这个:
custID = int(input("Customer ID: "))
executeStr = 'SELECT * FROM testrec WHERE ID=%s'%(custID,)
cursor.execute(executeStr, custID)
custData = cursor.fetchall()
if bool(custData):
pass
else:
print("Wrong Id")
而不是这个:
custID = int(input("Customer ID: "))
executeStr = "SELECT * FROM testrec WHERE ID=%d"
你应该写:
custID = int(input("Customer ID: "))
executeStr = "SELECT * FROM testrec WHERE ID='"+custID+"';"
我正在尝试使用 python 连接器从 MySQL 数据库中获取数据。我想获取匹配 ID
的记录。 ID 具有整数数据类型。这是代码:
custID = int(input("Customer ID: "))
executeStr = "SELECT * FROM testrec WHERE ID=%d"
cursor.execute(executeStr, custID)
custData = cursor.fetchall()
if bool(custData):
pass
else:
print("Wrong Id")
但是代码引发了一个错误:
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 '%d' at line 1
知道为什么整数占位符 %d
会产生这个吗?
字符串只接受 %s 或 %(name)s ,不接受 %d。
executeStr = "SELECT * FROM testrec WHERE ID=%s"
并且变量应该在一个元组中,尽管这会因您使用的版本而异,您可能需要使用:
cursor.execute(executeStr, (custID,))
这里有更多信息https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
current version支持的变量类型有:int
,long
,float
,string
,unicode
,bytes
,bytearray
,bool
,none
,datetime.datetime
,datetime.date
,datetime.time
,time.struct_time
,datetime.timedelta
,和 decimal.Decimal
您应该尝试 %s 而不是 %d。这是因为你的 MYSQL 的数据类型可能是 int 但你应该传递给 cursor 的参数必须是 string.
试试这个:
custID = int(input("Customer ID: "))
executeStr = 'SELECT * FROM testrec WHERE ID=%s'%(custID,)
cursor.execute(executeStr, custID)
custData = cursor.fetchall()
if bool(custData):
pass
else:
print("Wrong Id")
而不是这个:
custID = int(input("Customer ID: "))
executeStr = "SELECT * FROM testrec WHERE ID=%d"
你应该写:
custID = int(input("Customer ID: "))
executeStr = "SELECT * FROM testrec WHERE ID='"+custID+"';"