MySQLdb - 检查行是否存在 Python [英] MySQLdb - Check if row exists Python

查看:54
本文介绍了MySQLdb - 检查行是否存在 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 检查是否存在与我的数据库具有相同名称的行,但在这里无法完全得到它,这就是我正在尝试的:(我知道连接正在工作)

I am trying to check if a row exist with the same Name my database with python and can't quite get it here is what I am trying: (I know the connection is wokring)

try:
    cursor.execute("SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name"), (item_name)
catch:
     print "it does not exist"

有人能帮我吗

谢谢

推荐答案

  1. 首先,您的代码中有错误的语法.Python 没有 try...catch 块.它有 try...except像这样使用的块:

try:
    # something here
except:
    # something here

  1. 当您使用 SELECT 命令时,MySQL 不会返回错误.但是,您可以通过两种不同的方式确定它是否返回了某些内容.
  1. MySQL does not return an error when you use SELECT command. However there are two different ways you can find out if it returned something or not.

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")

另一种方法是获取语句并检查它是否为空:

Another way to do this would be to fetch the statement and check if it is empty:

# 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 编写代码.

Also i use Python 3 and pymysql, so there may be some syntax error but I have tried to write the code according to python 2.7 from what I could remember about it.

编辑(2020 年 5 月 1 日)

EDIT (5/1/2020)

感谢@Arishta 指出第一种方法要求您在使用 row_count 之前获取所有行.即在 row_count = cursor.rowcount

Thanks to @Arishta for pointing out that the first method will require you to fetch all rows before using row_count. i.e adding cursor.fetchall() before the 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")

如果您只关心记录是否存在,请使用 cursor.fetchone().

Use the cursor.fetchone() if you only care if the record exists or not.

这篇关于MySQLdb - 检查行是否存在 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆