pythonpython-3.xpymssql

Why is this double quotation mark error happening on print()?


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?


Solution

  • 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]))