Archive

Archive for the ‘MySQL’ Category

MySQL Connector/Python v0.3.2-devel released

January 10th, 2011 No comments

MySQL Connector/Python 0.3.2, a development release, is available for download:
https://launchpad.net/myconnpy/+download

Disclaimer: Since version 0.3 is still a development release, or ‘alpha’, it is not
recommended to run this in production.

MySQL Connector/Python 0.3.2-devel is a maintenance release fixing following bugs:

  • lp:701081 -Doesn’t install with Python 2.4

About MySQL Connector/Python: MySQL Connector/Python is implementing the
MySQL Client/Server protocol completely in Python. No MySQL libraries
are needed, and no compilation is necessary to run this Python DB API v2.0
compliant driver. It is compatible with Python v2.4 and later as well as
Python v3.1 and later.

Share

MySQL Connector/Python v0.3.1-devel released

January 7th, 2011 No comments

MySQL Connector/Python 0.3.1, a development release, is available for download:
https://launchpad.net/myconnpy/+download

Disclaimer: Since version 0.3.1 is still a development release, or ‘alpha’, it is not
recommended to run this in production.

MySQL Connector/Python 0.3.1-devel is a maintenance release fixing following bugs:

  • lp:695514 – Infinite recursion when setting connection client_flags
  • lp:691836 – Incorrect substitution by cursor.execute when tuple args contains ‘%s’

About MySQL Connector/Python: MySQL Connector/Python is implementing the
MySQL Client/Server protocol completely in Python. No MySQL libraries
are needed, and no compilation is necessary to run this Python DB API v2.0
compliant driver. It is compatible with Python v2.4 and later as well as
Python v3.1 and later.

Share

Setting client flags with MySQL Connector/Python

January 5th, 2011 2 comments

Setting client flags with MySQL Connector/Python works a bit differently than the other MySQL Python drivers. This blog post describes how to set and unset flags, like the CLIENT_FOUND_ROWS.

The default client flags for the MySQL Client/Server protocol can be retrieved using the constants.ClientFlag class:

>>> from mysql.connector.constants import ClientFlag
>>> defaults = ClientFlag.get_default()
>>> print ClientFlag.get_bit_info(defaults)
['SECURE_CONNECTION', 'TRANSACTIONS', 'CONNECT_WITH_DB',
 'PROTOCOL_41', 'LONG_FLAG', 'MULTI_RESULTS',
 'MULTI_STATEMENTS', 'LONG_PASSWD']

To set an extra flag when connecting to MySQL you use the client_flags argument of connect()-method. For example, you’d like to have the CLIENT_FOUND_ROWS set:

import mysql.connector
from mysql.connector.constants import ClientFlag
extra_flags = [ClientFlag.FOUND_ROWS]
cnx = mysql.connector.connect(client_flags=extra_flags)

Similar, you can unset a flag passing a list of negative values, or all at the same time. For example, you’d like the CLIENT_FOUND_ROWS set, but you don’t want CLIENT_MULTI_STATEMENTS:

import mysql.connector
from mysql.connector.constants import ClientFlag
extra_flags = [ClientFlag.FOUND_ROWS, -ClientFlag.MULTI_STATEMENTS]
cnx = mysql.connector.connect(client_flags=extra_flags)

It is also possible to pass the client_flags an integer, but you need to get first the defaults, and do bitwise operations to set/unset flags yourself. At the moment of writing, there is a bug about this, see lp:695514, but I recommend using the list-method.

Share

MySQL v5.5 and Python

December 17th, 2010 2 comments

MySQL v5.5 is GA, but is it working with Python? Yes, it does. Below you’ll find some quick, small tests I did with MySQLdb, oursql and our own MySQL Connector/Python.

My desktop is a Mac, but when it works on that, I’m sure it works elsewhere too. If not, just let us know!

MySQL for Python (aka MySQLdb)

Installing MySQL v5.5.8 64-bit from tar ball on MacOS X 10.6, it compiled fine and the module loaded giving me the expected result:

>>> import MySQLdb
>>> cnx = MySQLdb.connect(user='root')
>>> cur = cnx.cursor()
>>> cur.execute("SELECT VERSION()")
1L
>>> print cur.fetchall()
(('5.5.8',),)

oursql

oursql is an alternative for MySQLdb. Both are using the MySQL C API and thus need to be compiled from source (if you don’t find binaries of course).

>>> import oursql
>>> cnx = oursql.connect(user='root')
>>> cur = cnx.cursor()
>>> cur.execute("SELECT VERSION()")
>>> print cur.fetchall()
[(u'5.5.8',)]

MySQL Connector/Python

Our own MySQL Connector/Python doesn’t need compiling and doesn’t need any MySQL software installed to be able to connect to a MySQL server. Current unittests run fine against MySQL v5.5.8.

>>> cnx = mysql.connector.connect(user='root')
>>> cur = cnx.cursor()
>>> cur.execute("SELECT VERSION()")
-1
>>> print cur.fetchall()
[(u'5.5.8',)]

Conclusion

One can’t really conclude anything with the simple tests above, but it looks like MySQL v5.5 will work fine with Python.

Share
Tags: , ,

This blog served by MySQL v5.5

December 17th, 2010 No comments

MySQL v5.5 is GA and my blog, using WordPress 3.0, runs on it.

My personal highlight of this new MySQL version? The fact that it is released by Oracle.

Share
Tags: ,

MySQL Connector/Python 0.3.0 has been released!

December 10th, 2010 1 comment

MySQL Connector/Python 0.3.0, a development release, is available for download:
https://launchpad.net/myconnpy/+download

Since version 0.3.0 is still a development release, or ‘alpha’, it is not
recommended to run this in production.

MySQL Connector/Python 0.3.0 adds following features:

  • Python v2.4 support is back.
  • Support for compressed protocol.
  • Support for SSL connections (when Python’s ssl module is available).
  • Support for packets which are bigger than 16MB.
  • Max allowed packetsize defaults to 1GB.
  • Some performance improvements.

See the ChangeLog for extra details.

Please report bugs and comments using the bug tracker on Launchpad:
https://bugs.launchpad.net/myconnpy

About MySQL Connector/Python: MySQL Connector/Python is implementing the
MySQL Client/Server protocol completely in Python. No MySQL libraries
are needed, and no compilation is necessary to run this Python DB API v2.0
compliant driver. It is compatible with Python v2.4 and later as well as
Python v3.1 and later.

Share

Query caching with MySQL Connector/Python

November 22nd, 2010 2 comments

This blog post shows how to create a cursor class for MySQL Connector/Python which will allow you to cache queries. It will hold the query itself and the result in a global variable.

Note: this is a proof of concept and is only meant as a demonstration on how to extend MySQL Connector/Python.

Why query caching?

You are doing lots of queries that have the same result. It would be expensive to always run the same exact query. MySQL has already a query cache, and there is also memcached. But you like MySQL Connector/Python so much you’d like to do it yourself.

A cursor caching queries and their result

To demonstrate a simple implementation of a query cache, we inherit from an existing class: MySQLCursorBuffered. It will save the executed operation with their results in a ‘global’ variable. We call this cursor MySQLCursorQueryCache.

We take the buffered cursor because we’d like to save the result right away. Below you see we only changed two methods for MySQLCursorBuffered:

  • .execute(): it will now first check using an md5 checksum whether we executed the query before. If we did, we set the make the cached result active. If not, we simply executed.
  • ._handle_resultset(): called when .execute() did an operation which has a result set. The result we know save in the QUERY_CACHE global dict.
from hashlib import md5
import mysql.connector

QUERY_CACHE = dict()

class MySQLCursorQueryCache(mysql.connector.cursor.MySQLCursorBuffered):
    def execute(self, operation, params=None):
        self._qmd5 = md5(operation).digest()
        if QUERY_CACHE.has_key(self._qmd5):
            (self._rows, eof) = QUERY_CACHE[self._qmd5]
            self.rowcount = len(self._rows)
            self._handle_eof(eof)
            self._next_row = 0
        else:
            super(MySQLCursorQCache, self).execute(operation, params)

    def _handle_resultset(self):
        (self._rows, eof) = self.db().protocol.get_rows()
        self.rowcount = len(self._rows)
        self._handle_eof(eof)
        self._next_row = 0
        QUERY_CACHE[self._qmd5] = (self._rows, eof)
        try:
            self.db().unread_result = False
        except:
            pass
        self._qmd5 = None

The above code is a proof of concept, there is lots of room for improvement. For example, you need something to invalidate entries in the query cache.

How to use MySQLCursorQueryCache

def main():

    cnx = mysql.connector.connect(database='test')
    cur = cnx.cursor(cursor_class=MySQLCursorQueryCache)

    cur.execute("SELECT NOW()")
    print cur.fetchone()
    time.sleep(2)
    cur.execute("SELECT NOW()")
    print cur.fetchone()

    cur.close()
    cnx.close()

When you would use the default cursor, both executed SQL statements would produce a different result. The above produces the following output:

(datetime.datetime(2010, 11, 22, 21, 20, 4),)
(datetime.datetime(2010, 11, 22, 21, 20, 4),)

When you’d like to have some statements cached, and some not, just create a second cursor cursor_class=MySQLCursorBuffered (see Buffering results with MySQL Connector/Python).

Share

Buffering results with MySQL Connector/Python

November 21st, 2010 No comments

MySQL Connector/Python doesn’t buffer results by default. This means you have to fetch the rows when you issued a SELECT. This post describes how you can change this behavior.

Why buffering result sets?

Buffering or storing the result set on the client side is handy when you, for example, would like to use multiple cursors per connection and you’de like to traverse each one interleaved.

Keep in mind that with bigger result sets, the client side will use more memory. You just need to find out for yourself what’s best. When you know result sets are mostly small, you might opt to buffer.

MySQLdb by default buffers results and you need to use a different cursor to disable it. oursql does not buffer by default. This is good to know when you start using a different MySQL DB API for Python.

Use case: 1 connection, fetch from 2 cursors

You want to fetch data from two tables and process the data using one connection. If you do it without buffering, you would run into the following:

>>> cnx = mysql.connector.connect(database='test')
>>> cur1 = cnx.cursor()
>>> cur2 = cnx.cursor()
>>> cur1.execute("SELECT c1 FROM t1")
-1
>>> cur2.execute("SELECT c1 FROM t1")
..
mysql.connector.errors.InternalError: Unread result found.

MySQL Connector/Python offers two ways to turn buffering on or off. Either per connection or per cursor using the buffered argument set to True

Set buffering per connection

If you want all the cursors for a particular connection to be buffered, you can turn it on when connecting to MySQL setting the buffered-argument to True.

>>> import mysql.connector
>>> cnx = mysql.connector.connect(database='test',buffered=True)
>>> cur1 = cnx.cursor()
>>> cur1.__class__
<class 'mysql.connector.cursor.MySQLCursorBuffered'>
>>> cur2 = cnx.cursor()
>>> cur1.execute("SELECT c1 FROM t1")
3
>>> cur2.execute("SELECT c1 FROM t1")
3
>>> cur1.fetchone()
(u'Geert',)
>>> cur2.fetchone()

Set buffering per cursor

You can request a buffering cursor buffering from the connection object. Do this use the buffered-argument set to True:

>>> import mysql.connector
>>> cnx = mysql.connector.connect(database='test')
>>> <strong>cur1 = cnx.cursor(buffered=True)</strong>
>>> cur1.__class__
<class 'mysql.connector.cursor.MySQLCursorBuffered'>

Note: the above should work with MySQL Connector/Python v0.2 or greater

Share

Fetching rows as dictionaries with MySQL Connector/Python

October 13th, 2010 2 comments

This post describes how to make a custom cursor returning rows as dictionaries using MySQL Connctor/Python v0.2 (or later).

Problem: you want to fetch rows from the database and return them as a dictionary with keys being the column names.

First, lets check how you would do it without any custom cursor.

cnx = mysql.connector.connect(host='localhost',database='test')
cur = cnx.cursor()
cur.execute("SELECT c1, c2 FROM t1")
result = []
columns = tuple( [d[0].decode('utf8') for d in cur.description] )
for row in cur:
  result.append(dict(zip(columns, row)))
pprint(result)
cur.close()
cnx.close()
1

The above results in an output like this:

1
[{u'c1': datetime.datetime(2010, 10, 13, 8, 55, 35), u'c2': u'ham'},
 {u'c1': datetime.datetime(2010, 10, 13, 8, 55, 38), u'c2': u'spam'}]

Alternatively, you can code your own cursor which will return a row as a dictionary. Here is an example on how to do this:

import mysql.connector

class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):

  def fetchone(self):
    row = self._fetch_row()
    if row:
      return dict(zip(self.column_names, self._row_to_python(row)))
    return None

What we did is subclassing MySQLCursor and overload the fetchone()-method. To use the above, you can do following:

cnx = mysql.connector.connect(host='localhost',database='test')
cur = cnx.cursor(cursor_class=MySQLCursorDict)
cur.execute("SELECT c1, c2 FROM t1")
rows = cur.fetchall()
pprint(rows)
cur.close()
cnx.close()

The trick is to pass the cursor_class-argument when creating the cursor. (At the time of writing, I realize that the cursor_class should be part of the connection arguments to set a default for all requested cursors. We’ll change that.)

It’s a bit more elegant coding and possibilities are endless. Maybe you’d like a cursor which returns a row in XML for example.

Share

MySQL Connector/Python 0.2-devel available

October 13th, 2010 No comments

Next development release v0.2.0 of MySQL Connector/Python is available for download and testing. We still don’t recommend to use it in production: it is not beta or GA yet, but we are getting there.

Bug reports and feature requests are welcome through the Launchpad bug tracking tool.

Highlights:

  • .executemany() now optimizes INSERT statements using the MySQL
    multiple row syntax.
  • Setting sql_mode and time_zone when connecting as well as collation.
  • Raw Cursors can be used when you want to do the conversion yourself.
  • Unittests now bootstrap own MySQL server instance.
  • Tidying the source tree.

Full list of changes and bug fixes can be found online or in the ChangeLog-file, part of the distribution.

About MySQL Connector/Python: MySQL Connector/Python is implementing the MySQL Client/Server protocol completely in Python. No MySQL libraries are needed, and no compilation is necessary to run this Python DB API v2.0 compliant driver. It is compatible with Python v2.5 and later as well as Python v3.1 and later.

Share