4

This is my code so far. I'm attempting to print No results found if no results are returned by MySQL however I can't figure it out. Perhaps I'm using incorrect arguments. Could anyone provide me with an example? Much appreciated!

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]
4

4 回答 4

6

When you execute a select statement, cursor.rowcount is set to the number of results retrieved. Also, there is no real need to call cursor.fetchall(); looping over the cursor directly is easier:

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]

Note that I also switched your code to use SQL parameters; there is no need to use string interpolation here, leave that to the database adapter. The %s placeholder is replaced for you by a correctly quoted value taken from the second argument to cursor.execute(), a sequence of values (here a tuple of one element).

Using SQL parameters also lets a good database reuse the query plan for the select statement, and leaving the quoting up to the database adapter prevents SQL injection attacks.

于 2013-10-15T13:29:20.250 回答
0

You could use cursor.rowcount after your code to see how many rows were actually returned. See here for more.

于 2013-10-15T13:28:38.013 回答
0

I guess, this should work.

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])
    rows = cursor.fetchall()
    if not rows:
        print 'No resulrs found'
        return
    for row in rows:
        print row[1]

Note, that I changed the way the film parameter is passed to query. I don't know, how exactly it should be (this depends on what MySQL driver for python you use), but important thing to know, is that you should not pass your parameters directly to the query string, because of security reasons.

于 2013-10-15T13:29:18.067 回答
-2

You can also use :

rows_affected=cursor.execute("SELECT ... ") -> you have directly the number of returned rows

于 2013-10-15T13:35:21.597 回答