tags:

views:

152

answers:

3

Is there another way to connect to a MySQL database with what came included in the version of Python (2.5.1) that is bundled with Mac OS 10.5.x? I unfortunately cannot add the the MySQLdb module to the client machines I am working with...I need to work with the stock version of Python that shipped with Leopard.

+5  A: 
unutbu
That was helpful ,thanks -- In thinking further, I am not committed to using MySQL -- so I may change the db to sqlite -- I was worried about scalablity of it, but it may do what I need to do since the sqlite3 module is already there on the client machines...
CaseyIT
`subprocess.call` returns `returncode` (an integer); the output from `mysql` goes to process' stdout/stderr and `retval` is just an integer.
J.F. Sebastian
@J.F. Sebastian: Oops! Thanks for catching that. I've fixed my code.
unutbu
A: 

You can simplify parsing the data returned by a command line batch call on mysql by using os.popen() rather than subprocess.call(), and modifying the query in the command.

  • Dropping the command into os.popen(cmd).readlines() get the output as a list of returned lines, with records separated by a tab character.
  • mysql option '-e' rather than '-Bse' returns a record or line with the names of the fields returned.

The output can now be put into a list of dictionaries keyed on the table fields names:

import os    
res = os.popen(cmd).readlines()
dicts = [dict(zip(res[0].split('\t'), record.split('\t'))) for record in res[1:]]

Caveats:

  • Defaults in mysql installations for field separators might vary. To ensure (or know) a consistent separator character you might have interact with the mysql installation to set (or discover) its default.
  • You might have to redo the command line passed to os.popen as a string, I don't know if os.popen supports submission of list objects as arguments.
  • This worked on a linux box. I don't know why a Mac would be any different.
  • I am but an egg and cannot comment on the advantages of subprocess.call() over os.popen(). I read in that popen() opens another process, and that its cousin os.system blocks the caller until answered.

This just cleans up a hack. You are probably still better off finding a way to use MySQLdb, or something similar for another database.

UPDATE: The Python library reference offers some more possibilities.
- If you really want to see the errors or warnings sent to standard error by mysql, use popen3.
- The Python documentation mentions popen4, which 'executes cmd as a subprocess'. Might get around blocking issues?

chernevik
+1  A: 

Or you could check out MySQL Connector/Python. It's still in development, but should work with Python 2.5. No MySQL libraries or other software needed.

geertjanvdk
Thanks, that looks interesting..
CaseyIT