spikesource hints'n'tips

Our Top Tags

                                       

Mailing List

Keep uptodate with the latest hints'n' tips as they are published by signing up to our mailing list.

Our RSS Feeds








Latest Linux News

20 Beautiful Dark Themes for Gnome and Ubuntu

Tuesday, 19 August 2008
Cats Who Code: "Some weeks ago, I shown you a list of 30 themes for enhancing your Gnome desktop."

OpenSolaris: a Linux Admin's View

Tuesday, 19 August 2008
Linux Format: "Sun is battling hard to break into the open source operating system world with OpenSolaris. Juliet Kemp takes it for a test-drive, sampling its unique features and seeing how it fares a

What's That They Say About Assumptions?

Tuesday, 19 August 2008
Blog of Helios: "Sometimes Linux isn't the answer."

The Brampton Factor: Analysts Fail on Open Source

Tuesday, 19 August 2008
IT Pro: "For open source software to achieve its full potential, people's perceptions must change. Yet how can that happen when open source is so woefully neglected by analysts, asks Martin Brampton."

Why Red Hat Invested In JBoss Instead Of Linux Desktops

Tuesday, 19 August 2008
The VAR Guy: "Ever wonder why Red Hat spends so much time focused on the JBoss middleware market and so little time trying to make Linux a desktop standard? The answer involves some simple but startli

Latest Digg Entries

Introduction to using MySQLdb with python

posted Saturday, 10 September 2005

What is MySQLdb?

MySQLdb is a python interface to MySQL It follows the python DB API (PEP-0249) which is analagous to JDBC in java. Ideally when using this API one should be able to easily port to another database.

How do I install the MySQLdb?

First see if MySQLdb is already installed by doing the following from a python shell:

>>> import MySQLdb
If you see an error message like the one below, then it isn't installed.
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   ImportError: No module named MySQLdb
If you get no error message then, the interface is already installed.

The remainder of this article will explain how to install mysqldb from the source. (Note that my distributions provide binary packages as well).

  1. Download a recent version from the project homepage.

  2. Perform the following from a shell (unix):

      $ tar xfz MySQL-python-1.2.0.tar.gz
      $ cd MySQL-python-1.2.0
      $ python setup.py build
      $ su # or use sudo
      # python setup.py install
    
  3. Peform the import test above to see that the install worked.

The basics

The basic flow of interacting with a database using the DB-API consists of:
  1. Importing the api module

  2. Acquiring a connection

  3. Issuing SQL statements

  4. Closing the connection

A basic example

Here's a simple example showing all of the steps above. It connects to a database named dbname on the machine named host machine. It selects all of the content from the simpletable table and stores the first row in a variable called data. The connection is then closed to the database:
  import MySQLdb
  db = MySQLdb.connect("host machine", "dbuser", "password", "dbname")
  cursor = db.cursor()
  sql = """SELECT * FROM simpletable"""
  cursor.execute(sql)
  data = cursor.fetchone()
  db.close()

Related Links

tags:    

links: digg this    del.icio.us    technorati    




1. Alexandro Colorado left...
Monday, 17 October 2005 4:12 pm :: http://es.openoffice.org

Interesting post, I enjoyed it and helped me with my python script.

This script however does a bit more, since it combines the **urllib2 module** which parse the HTML from a static website, load it into an array and load them into a local mysql database.

This is cool for retrieving content out of external websites.

#!/usr/bin/env python
# -*- coding: latin-1 -*-

headlines_url = "http://es.openoffice.org/servlets/ProjectNewsList"

import HTMLParser
import urllib2
import MySQLdb

class HeadlinesParser(HTMLParser.HTMLParser):
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.headlines = {}
        self.while_anchor = False
        self.last_href = None

    def handle_starttag(self, name, attrs):
        attrs = dict(attrs)
        if name == "a":
            if "href" in attrs:
                current_href = attrs["href"]
                if "newsItemID" in current_href:
                    self.while_anchor = True
                    self.last_href = current_href

    def handle_data(self, content):
        content = content.strip()
        if self.while_anchor:
            self.headlines[content] = self.last_href

    def handle_endtag(self, name):
        if name == "a":
            self.while_anchor = False


def conectarBD():
    """Rutina de conexión a la BBDD"""

    try:
        db = MySQLdb.Connect(host='localhost',user='myuser',passwd='mypassw
ord',db='mydatabase')
        return db
    except:
        print u"Error en la conexion a la Base de Datos"
        return -1

def insertarHeadLines(datos):
    """Funcion para insertar los enlaces en mysql"""

    conn = conectarBD()
    c    = conn.cursor()

    if (conn != -1):
        try:
            """Insertamos los links"""
            for headline in datos:
                c.execute('''INSERT INTO Headlines (headline, url) VALUES 
('%s', '%s')''' % ( headline ))
        except:
            print 'Problemas al realizar los «INSERT»'
            return -1

def main():
    """
        CREATE TABLE `Headlines` (
            `id` INT NOT NULL AUTO_INCREMENT COMMENT 'Identificador',
            `headline` VARCHAR(254) NOT NULL COMMENT 'Titular de la 
noticia',
            `url` VARCHAR(254) NOT NULL COMMENT 'Enlace a la 
noticia',
            INDEX `HL`(`headline`),
            PRIMARY KEY(`id`)
        )
        ENGINE = MYISAM
        DEFAULT CHARSET=latin1
        AUTO_INCREMENT = 1
        COMMENT = 'Almacen de enlaces de es.openoffice.org';
    """
    source = urllib2.urlopen(headlines_url).read()
    parser = HeadlinesParser()
    parser.feed(source)

    lineas = parser.headlines.items()

    try:
        insertarHeadLines(lineas)
    except:
        print 'Problemas al insertar los enlaces.'


if __name__ == "__main__":
    main()


2. Ok left...
Sunday, 29 January 2006 9:43 pm :: http://www.enlargementworks.com

Great content.


3. Aydin left...
Saturday, 5 January 2008 9:28 pm

aydin@aydin-ubuntu:~/Desktop/MySQL-python-1.2.2$ python setup.py build Traceback (most recent call last):

  • File "setup.py", line 5, in <module>

    • import ez_setup; ez_setup.use_setuptools()

  • File "/home/aydin/Desktop/MySQL-python-1.2.2/ez_setup.py", line 85, in use_setuptools

    • import setuptools; setuptools.bootstrap_install_from = egg

zipimport.ZipImportError: can't decompress data; zlib not available


4. Aydin left...
Saturday, 5 January 2008 9:29 pm

can anyone help me with this error? aydin@aydin-ubuntu:~/Desktop/MySQL-python-1.2.2$ python setup.py build Traceback (most recent call last):

  • File "setup.py", line 5, in <module>

    • import ez_setup; ez_setup.use_setuptools()

  • File "/home/aydin/Desktop/MySQL-python-1.2.2/ez_setup.py", line 85, in use_setuptools

    • import setuptools; setuptools.bootstrap_install_from = egg

zipimport.ZipImportError: can't decompress data; zlib not available


5. Filéfisk left...
Tuesday, 22 January 2008 9:02 pm

Aydin: As you're using ubuntu you might as well do: sudo apt-get install python-mysqldb


Related Posts

Putting a MySQL query to sleep

Tuesday, 10 October 2006 8:05 A GMT
There are a number of reasons why you would want to put a MySQL query to sleep, here is how.

Resetting the root password on MySQL and managing legacy password access

Friday, 18 August 2006 3:16 P GMT
If you need to use an old client library with MySQL 5, or you need to reset the root mysql password, this entry looks at both.

Http client using digest authentication (in python)

Wednesday, 14 September 2005 8:00 A GMT
To test mod_auth_digmysql, you needed to test that it works so here are some testcases in python.

Introduction to using MySQLdb with python

Saturday, 10 September 2005 9:31 A GMT
MySQLdb is the Python DB API-2.0 interface and this blog looks at the using the MySQL from Python

How to backup and import a MySQL InnoDB database

Tuesday, 16 August 2005 10:56 A GMT
Details how to properly backup and then restore a Mysql database running Innodb as oppose to MyISAM.