【问题标题】:MySQLdb - Check if row exists PythonMySQLdb - 检查行是否存在 Python
【发布时间】:2015-10-19 22:55:37
【问题描述】:

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

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

谁能帮帮我

谢谢

【问题讨论】:

  • @VigneshKalai 当项目确实存在时它会抛出异常

标签: python mysql


【解决方案1】:
  1. 首先,您的代码中有错误的语法。 Python 没有 try...catch 块。它有 try...except 块,使用如下:
try:
    # something here
except:
    # something here
  1. 当您使用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()

【讨论】:

  • 很好的第一个答案,继续努力:^) 另见EXISTS MySQL 关键字。
  • 谢谢,是的,'Exists' 确实看起来更好,因为它在返回一行后停止迭代。
  • 谢谢,它有效。不过,您需要在 print 语句周围加上括号。
  • @Dan cook 回答了 Python 2.7 的问题,它的语法与 Python 3 及更高版本不同
  • 您第一种直接使用行计数而不首先获取行的方法将不起作用。无论实际行数如何,它都将始终返回 0。该文档指出:“对于非缓冲游标,在调用行获取方法之前不会从服务器获取行。在这种情况下,您必须确保在执行任何其他语句之前获取结果集中的所有行。连接”
【解决方案2】:
cursor.execute("SELECT * FROM userinfo WHERE User_Name=%s",(userid,))
data="error" #initially just assign the value
for i in cursor:
    data=i #if cursor has no data then loop will not run and value of data will be 'error'
if data=="error":
    print("User Does not exist")
else:
    print("User exist")

【讨论】:

    【解决方案3】:

    如果您想检查空结果,请尝试if cur.description is None

    if cursor.description is None:
        # No recordset for INSERT, UPDATE, CREATE, etc
        pass
    else:
        # Recordset for SELECT
    

    还有:

    exist = cursor.fetchone()
    if exist is None:
      ... # does not exist
    else:
      ... # exists
    

    如果您正在运行的语句从不返回结果集 (比如INSERT没有RETURNING,或者SELECT ... INTO),那么你 无需拨打.fetchall();不会有结果集 此类声明。调用.execute() 足以运行语句。

    【讨论】:

      猜你喜欢
      • 2017-03-03
      • 1970-01-01
      • 2013-12-25
      • 2015-01-04
      • 2021-11-15
      • 2016-11-05
      • 2012-02-19
      • 1970-01-01
      • 2020-02-23
      相关资源
      最近更新 更多