Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyodbc and mySQL

I am unable to connect to mySQl db using pyodbc.

Here is a snippet of my script:

import pyodbc
import csv

cnxn = pyodbc.connect("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost;DATABASE=mydb; UID=root; PASSWORD=thatwouldbetelling;") 
crsr = cnxn.cursor()

with open('C:\\skunkworks\\archive\\data\\myfile.csv','r') as myfile:
    rows = csv.reader(myfile, delimiter=',', quotechar='"')
    for row in rows:
        insert_str = 'INSERT into raw_data VALUES(something, something)'
        print insert_str
        #crsr.execute(insert_str)
    cnxn.commit()
    myfile.close()

I get this error at the pyodbc.connect() line:

pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnectW)')

I have another question regarding this error (and Python scripts in general). When I run this as a script, it fails silently (I was expecting a stack trace). I have to type each line in manually to find where the error occured.

I am being a bit lazy for now (no exception handling) - is this normal behaviour of a Python script without exception handling to fail silently?

[Edit]

I am not using mysqldb because I am already using pyodbc to extract my data from another source (MS Access). Ok, not a good reason - but I am already grappling with pyodbc and I dont really fancy having to wrestle with another library/module/package(whatever its called in Python) for a "one off" job. I just want to move my data of from various data sources in the Windows environment to mySQl on Linux. once on Linux, I'll be back on terra firma.

That is the entire 'script' right there. I just saved the code above into a file with a .py extension, and I run python myscript.py at the command line. I am running this on my XP machine

like image 405
skyeagle Avatar asked Oct 20 '10 20:10

skyeagle


1 Answers

I had this same mistake so I went over all the version I was using for the connection. This is what I found out:

For Python 2.7 32 bits: - pyodbc must be 32bits - the DB Driver must be 32bits. (Microsoft Access should be 32 bits too)

For those who use the 64 bits version. You should check that everything is 64 bits too.

In my case I was trying to connecto to an Oracle DB and Microsoft Access DB so I had to make the following components match the architechture version:

  • pyodbc (MS Access)
  • python
  • cx_Oracle (Oracle dialect for SQLalchemy)
  • Oracle instantclient basic (Oracle. Do not forget to create the environment variable)
  • py2exe (Making the excecutable app)
like image 142
Alejandro Avatar answered Oct 02 '22 17:10

Alejandro