2

I am trying to connect to MYSQl db Server using pyodbc module.

with pyodbc.connect('DRIVER={MySQL ODBC 5.6 Driver};SERVER=XX.XX.X.XX;PORT=3306;DATABASE=ssc;UID=Pra;PASSWORD=welcome;') as cnxn:

    cursor = cnxn.cursor()
    cursor.execute('insert into ....')

When I ran the above code in python I am encountering an error 'local variable 'cnxn' referenced before assignment'I am working on MySQL workbench 6.2 and I am not sure which version of MySQL driver to use.

Pranay
  • 71
  • 2
  • 4

2 Answers2

1

This specific error isn't a problem with the driver, the cnxn object is never created.

Change your code to:

cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.6 Driver};SERVER=XX.XX.X.XX;PORT=3306;DATABASE=ssc;UID=Pra;PASSWORD=welcome;')
cursor = cnxn.cursor()
cursor.execute('insert into ....')

The pyodbc wiki has a getting started section that is helpful.

For further reading, see pyodbc issue 100 concerning use of with.

Bryan
  • 17,112
  • 7
  • 57
  • 80
  • I tried what you suggested and I printed the stack trace this is an the error that I got '('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) '.The exact connect statement that I am using is this cnxn= pyodbc.connect('DRIVER={MySQL Driver};SERVER=localhost;PORT=3306;DATABASE=ssc;UID=Pra;PWD=welcome;OPTION=3') – Pranay Dec 05 '14 at 14:22
  • @Pranay Now you're seeing the driver problem. Similar question [here](http://stackoverflow.com/questions/3982174/pyodbc-and-mysql?rq=1). – Bryan Dec 05 '14 at 14:35
0

Why don't you try using the MySQL driver for Python?

pip install MySQL-python
FlipperPA
  • 13,607
  • 4
  • 39
  • 71