T.Gilmour
T.Gilmour

Reputation: 43

SQL query only selecting first result

I want to retrieve all songIDs that are associated with the userID that I input but it only prints the first result.

database: enter image description here

My code:

enter = raw_input('Enter UserID: ')
cursor = MusicData.cursor()
sql = "SELECT * FROM (SELECT songID FROM train WHERE userID=? )"
result = cursor.execute(sql,(enter,))
print result.fetchall()[0][0],
Enter UserID: 3a613180775197cd08c154abe4e3f67af238a632
SODOZXB12A8C13CD55

Upvotes: 0

Views: 2313

Answers (4)

Kishan Tripathi
Kishan Tripathi

Reputation: 16

The problem is with your print statement. Right now by giving print result.fetchall()[0][0] you are asking python to print one element. Use

for item in result.fetchall():
    print item

Upvotes: 0

T.Gilmour
T.Gilmour

Reputation: 43

I fixed it by adding a for loop of fetchall()

rows = result.fetchall()
for row in rows:
    print row

Upvotes: 0

Pavel Kovtun
Pavel Kovtun

Reputation: 367

Add "LIMIT NN" to your SQL request. That will limit an output to NN number of rows:

sql = "SELECT * FROM Table LIMIT 5"

Will give you only 5 rows.

on MS SQL DB it should be the "TOP" keyword:

sql = "SELECT TOP 5 * FROM Table"

Upvotes: 0

Florian Fray
Florian Fray

Reputation: 274

You're only showing the first rows first column due to [0][0] after in this line print result.fetchall()[0][0]

Upvotes: 1

Related Questions