Home > DBA > Using Python to work with MySQL – part 1

Using Python to work with MySQL – part 1

If you are a python developer and will need some querys in MySQL, please read this post. To begin, we will need an API to work with MySQL databases, I will use MySQLdb.

We will need MySQLdb API installed on machine, I won´t talk about it now, please wait another post(very soon).

First: We need to import the MySQL API

import MySQLdb

Second: We will connect, using the method connect()

db=MySQLdc.connect(passwd=”my_password”,”db=gabriel”)

And now, go to the queries! :P

- We need a cursor,

gabriel=db.cursor()

- and after we will execute queries on it:

max_price=3000
gabriel.execute(“”"SELECT bike, computer, car FROM shop
WHERE price < %s”"”, (max_price,))

We use %s in the string to MySQLdb convert it to a literal value. The query will actually say, “…WHERE price < 5″

And now, the results:

>>> gabriel.fetchone()
(Spark23S, Macbook1XXs,PorscheCarrera )

Quite unlike the _mysql example, this returns a single tuple, which is the row, and the values are properly converted by default… except… What’s with the L’s?

As mentioned earlier, while MySQL’s INTEGER column translates perfectly into a Python integer, UNSIGNED INTEGER could overflow, so these values are converted to Python long integers instead.

If you wanted more rows, you could use c.fetchmany(n) or c.fetchall(). These do exactly what you think they do. On c.fetchmany(n), the n is optional and defaults to c.arraysize, which is normally 1. Both of these methods return a sequence of rows, or an empty sequence if there are no more rows. If you use a weird cursor class, the rows themselves might not be tuples.

Note that in contrast to the above, c.fetchone() returns None when there are no more rows to fetch.

Post changed and copied  from MySQLdb

Categories: DBA Tags: , ,
  1. John Fabiani
    March 25th, 2009 at 16:47 | #1

    Why reinvent the wheel? Checkout http://www.dabodev.com where accessing MySQL is done with ease. You will see lots of code that uses wxPython for the GUI. But none of it is required (GUI that is). Just create a connection string and start using MySQL

  1. No trackbacks yet.