-2

I am working on a simple python script for retrieving information from a mysql database. Here are my two examples which are almost IDENTICAL and the first successfully compiles while the second returns:

      File "dbconnection.py", line 17
    print ip
           ^
SyntaxError: invalid syntax

I have tried deleting the try catch code from the second example with no results though. There is a relevant post on syntax error on Python 3 which makes my second example successfully run but it doesn't answer the question "why these almost identical examples have different behavior".

First example:

import datetime
import mysql.connector

cnx = mysql.connector.connect(user='user', database='test', password='test')
cursor = cnx.cursor()

query = ("SELECT ip FROM guralps")
cursor.execute(query)

for (ip) in cursor:
  print ip

cursor.close()
cnx.close()

Second which does not compile:

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
from mysql.connector import errorcode
import time


try:

  cnx = mysql.connector.connect(user='user', database='test', password='test')
  cursor = cnx.cursor()

  query = ("SELECT ip FROM guralps")
  cursor.execute(query)

  for (ip) in cursor:
    print ip

  cursor.close()
  cnx.close()

except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exists")
  else:
    print(err)
else:
  cnx.close()
Community
  • 1
  • 1

2 Answers2

1

You used:

from __future__ import print_function

at the top of your module. This disables the print statement for that module so you can use the print() function instead:

print(id)

From the function documentation:

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

from __future__ import print_function
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • If a question is solved on stackoverflow, don't change the title to include "Solved" like on some fora. Here, just mark the answer that solved your question as "the accepted answer", as mentioned in stackoverflow's [tour](https://stackoverflow.com/tour). – Oliver W. Oct 30 '14 at 10:34
-1

from future import print_function, division require Python 2.6 or later. print_function will allow you to use print as a function. So you can't use it as print ip.

>>> from __future__ import print_function
>>>print('# of entries', len(dictionary), file=sys.stderr)
jack
  • 505
  • 2
  • 7