如果MySQL没有返回结果,则打印

Cat*_*Cat 4 python mysql python-2.7

到目前为止,这是我的代码。No results found如果MySQL没有返回结果,我正在尝试打印,但是我无法弄清楚。也许我使用了不正确的参数。谁能给我一个例子?非常感激!

def movie_function(film):
    connection = mysql connection info
    cursor = connection.cursor()
    sql = "SELECT * FROM film_database WHERE film_name = '"+film+"' ORDER BY actor"

    cursor.execute(sql)
    rows = cursor.fetchall()
    for row in rows:
        print row[1]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

执行select语句时,cursor.rowcount设置为检索到的结果数。同样,也没有真正的需要致电cursor.fetchall();直接循环游标更容易:

def movie_function(film):
    connection = mysql connection info
    cursor = connection.cursor()
    sql = "SELECT * FROM film_database WHERE film_name = %s ORDER BY actor"

    cursor.execute(sql, (film,))
    if not cursor.rowcount:
        print "No results found"
    else:
        for row in cursor:
            print row[1]
Run Code Online (Sandbox Code Playgroud)

注意,我也将您的代码切换为使用SQL参数。此处无需使用字符串插值,只需将其留给数据库适配器即可。的%s占位符被从第二个参数得到的正确地引用值替换为你cursor.execute(),值的序列(这里一个元素的元组)。

使用SQL参数还可以使一个好的数据库为select语句重用查询计划,并且将引用保留在数据库适配器中可以防止SQL注入攻击。