0

I'm learning to use Python 3.4 to connect to my SQL Server database. I'm using pymssql to connect to my database and one of the examples is throwing an error when SELECTING the data from a table and printing the output.

This is not all of the code. The first part of this code connects to the database and creates the table in the database if the table does not exist. This was successful. Connection was established, table was created, I can select the table and so forth.

Here is the code in question:

cursor.execute('SELECT id, name FROM persons WHERE salesrep=%s', 'John Doe')
row = cursor.fetchone()
while row:
    print "ID=%d, Name=%s" % (row[0], row[1])
    row = cursor.fetchone()

conn.close()

The error Python is showing is on the second double quotation mark:

print "ID=%d, Name=%s" % (row[0], row[1])

                     ^

I tested the SELECT statement, everything looks good there. From what I can tell, print looks good. So what am I missing?

Fastidious
  • 1,249
  • 4
  • 25
  • 43

1 Answers1

0

This is python3. print is a function in python3. This is the proper syntax:

print("ID=%d, Name=%s" % (row[0], row[1]))

Also, you should use the new string formatting syntax:

print("ID={0}, Name={1}".format(row[0], row[1]))
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • I hate my life. Thank you. A new error came up though in relation to a KeyError 0, which from what I can see is a dict error? What would cause an key error 0 on that same line of code? – Fastidious May 18 '14 at 03:56
  • @Fastidious, Are you sure there is a key called 0. Try printing row and seeing what keys it has. – sshashank124 May 18 '14 at 03:58
  • I did a print(row) and got back {'name': 'John Smith', 'id' : 1} – Fastidious May 18 '14 at 04:03
  • 1
    @Fastidious, In that case, you should do: `print("ID={0}, Name={1}".format(row['id'], row['name']))` – sshashank124 May 18 '14 at 04:05
  • Yeppers, already figured it out. Again, the python3 versus python2 I assume hehe. Thanks for the help. I guess it would be better if I used the right python version with the example being used. – Fastidious May 18 '14 at 04:07