MySQLdb - 检查行是否存在Python

时间:2015-07-29 06:02:55

标签: python mysql

我正在尝试检查一行是否存在与我的数据库相同的名称我的数据库与python并不能完全得到它是我正在尝试:(我知道连接是wokring)

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

有人可以帮助我吗

由于

3 个答案:

答案 0 :(得分:9)

  1. 首先,您的代码中的语法错误。 Python没有try...catch块。它有try...except块,使用方式如下:

    try:
        #something here
    except:
        #something here
    
  2. 使用SELECT命令时,MySQL不会返回错误。但是,有两种不同的方法可以确定它是否返回了某些内容。

  3. 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代码。

答案 1 :(得分:1)

如果您想检查空结果,请尝试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() 足以运行该语句。

答案 2 :(得分:0)

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