- 首先,您的代码中有错误的语法。 Python 没有
try...catch 块。它有 try...except 块,使用如下:
try:
# something here
except:
# something here
- 当您使用
SELECT 命令时,MySQL 不会返回错误。但是,您可以通过两种不同的方式来确定它是否返回了某些内容。
Python 2.7
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print "number of affected rows: {}".format(row_count)
if row_count == 0:
print "It Does Not Exist"
Python 3+
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print ("number of affected rows: {}".format(row_count))
if row_count == 0:
print ("It Does Not Exist")
另一种方法是获取语句并检查它是否为空:
# execute statement same as above
msg = cursor.fetchone()
# check if it is empty and print error
if not msg:
print 'It does not exist'
这是我的第一个答案,所以我不知道如何正确设置答案中的代码样式,因此看起来也很乱。很抱歉。
我还使用 Python 3 和 pymysql,所以可能存在一些语法错误,但我尝试根据我所记得的 Python 2.7 编写代码。
编辑(2020 年 5 月 1 日)
感谢@Arishta 指出第一种方法将要求您在使用 row_count 之前获取所有行。即在row_count = cursor.rowcount之前添加cursor.fetchall()
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# Add THIS LINE
results = cursor.fetchall()
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print("number of affected rows: {}".format(row_count))
if row_count == 0:
print("It Does Not Exist")
如果您只关心记录是否存在,请使用cursor.fetchone()。