- 首先,您的代码中的语法错误。 Python 没有
try...catch
堵塞。它有try...except https://docs.python.org/2/reference/compound_stmts.html#try块的使用方式如下:
try:
# something here
except:
# something here
- 使用时MySQL不会返回错误
SELECT
命令。但是,您可以通过两种不同的方法来确定它是否返回了某些内容。
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编写代码。
EDIT(2020 年 5 月 1 日)
感谢@Arishta 指出第一种方法将要求您在使用 row_count 之前获取所有行。即添加cursor.fetchall()
之前row_count = cursor.rowcount
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")
Use the cursor.fetchone()
如果你只关心记录是否存在。