Friday, November 24, 2006

Python and MySQL

I know how to work with JDBC in Java and DBI in perl.
But how about Python ? :)
Lets see... I have Windows box with Python 2.4 and MySQL 5.
OK. What do I need else ?
Some kind of driver, if Python-style interaction with DRBMS's
is similar to Java or Perl. I'm guess :) It is here.
So, we have "Python Database API Specification v2.0".
It is not a problem for now to write an dummy code
to play with API :


import
MySQLdb
import sys

try:
myDB = MySQLdb.connect(
host="127.0.0.1",
port=3306,user="root",
passwd="**********",
db="testdb")
cHandler = myDB.cursor()
cHandler.execute("SELECT * FROM testTable")

for a in range(cHandler.rowcount) :
result = cHandler.fetchone()
for x in range(len(result)) :
print result[x]
print "\n"

myDB.close()

except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(-1)

No comments: