jeudi 3 mars 2016

Sqlite SELECT statement fails in Python

I have been working to create a basic application that queries a database of records that I own to suggest what I should listen to next. My current draft requests that the user enter the current album that they are listening to and then queries the database to return the related genre, and other artists in that genre.

The c.execute and c.fetchone() commands that I use to return the artist and genre work twice. The code fails when I attempt to set reclist = c.fetchall()

The worst part of this entire thing is that I had the code working for a few minutes before going back and tinkering with a few things. I guess I've learned my lesson about making 'innocuous' changes.

Schema for the database:

sqlite> .schema
CREATE TABLE album (
id INTEGER PRIMARY KEY,
album TEXT
);
CREATE TABLE genre (
id INTEGER PRIMARY KEY,
genre TEXT
);
CREATE TABLE artist (
id INTEGER PRIMARY KEY,
artist TEXT
);
CREATE TABLE aag (
artist_id INTEGER,
album_id INTEGER,
genre_id INTEGER
);

Full Python code below:

import sqlite3
import sys

conn = sqlite3.connect('aag_database.db')
c = conn.cursor()

print "Are you listening to a record right now?"
uresponse1 = raw_input("[y / N]")

#collect query information from user
if uresponse1 == "N":
    sys.exit()

print "What is the name of the record are you listening to?"
uresponse2 = raw_input("> ")

print "Let me see what I know about %r" % (uresponse2)

#query record database
c.execute('''Select artist.artist FROM 
    artist, album, aag WHERE 
    artist.id=aag.artist_id AND
    album.id=aag.album_id AND
    album.album=?''', (uresponse2,))
artist_return = str(c.fetchone())

if artist_return == "None":
    print "I guess I don't know anything about that record."
    sys.exit()

#confirm match
print "Oh do you mean %r by %r" % (uresponse2, artist_return)

uresponse3 = raw_input("[y / N]")

if uresponse3 == "N":
    sys.exit()

#query record database for genre of user input
c.execute('''Select genre.genre FROM 
    genre, album, aag WHERE 
    genre.id=aag.genre_id AND 
    album.id=aag.album_id AND 
    album=?''', (uresponse2,))
genre_return = str(c.fetchone())

if genre_return == "None":
    print "I guess I don't know anything about that genre."
    sys.exit()

#confirm match
print "I would classify that album as %r music" % (genre_return)

print "If you like that you may also enjoy these records:"

#query record database on genre
c.execute('''Select artist, album FROM 
    genre, album, artist, aag WHERE 
    genre.id=aag.genre_id AND 
    album.id=aag.album_id AND 
    artist.id=aag.artist_id AND
    genre.genre=?''', (genre_return,))
reclist = c.fetchall()

print reclist

Aucun commentaire:

Enregistrer un commentaire