Skip to content
Advertisement

How to stop a search into a database when I already have results

I will post my code and explain after:

db = sqlite3.connect("Gene.sqlite")
cur = db.cursor()
cur.execute("SELECT * FROM Table")
for i in cur.fetchall():
    if i[0] == name:
    print '<br>' '<c><b>TYPE'':</b>' ' '+ i[1]+ '<br>'
    '<b>DESCRIPTION:</b></c>' ' '+ i[2]
    break
else:
    print 'This name does no exist in the Database'

This is in python and I am creating a CGI script where the user inputs a name, and my script goes into that database, searches for the name and prints out the row for that name. I have a database with a table called Table with thousands of names, I just want the user to input a name, and have it search through the table, and find one single name that matches the input, and if the name exists, print the necessary information (as shown). However, for every name that does not match, it prints This name does not exist until it finds a match, and if a match isn’t found, i just get thousands of messages saying “this name does not exist”. Basically, I want it to search the table without printing anything UNTIL it finds the name, and if it finds the name, prints out the information, and if it does not exist, just print once “This name does not exist int the database”.

Advertisement

Answer

You need to use a WHERE clause:

db = sqlite3.connect("Gene.sqlite")
cur = db.cursor()
looking_for = 'hello'
cur.execute("SELECT type,description FROM Table WHERE name = '%s'", (looking_for,))
for i in cur.fetchall():
    result = '<br><c><b>TYPE:</b> {}<br><b>DESCRIPTION:</b></c> {}'
    print result.format(*i)
else:
    print '{} does not exist in the Database'.format(looking_for)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement