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

Hosted Zimbra Email Catches On With Managed Service Providers

Saturday, 19 July 2008
MSPmentor: "When it comes to hosted email, why zig when you can zag? That explains the strategy at EtomicMail, a managed service provider that’s hosting Zimbra — an open source email platf

An Open Source Seeing Eye Dog for Web Surfers

Saturday, 19 July 2008
LinuxInsider: "WebAnywhere is an open source, Web-based application that acts as a screen reader of sorts for blind people. Its developer, a student at the University of Washington, designed it so tha

Perl and Bash Versions Of Binary To Decimal Conversion Script

Saturday, 19 July 2008
The Linux and Unix Menagerie: "As promised, in yesterday's post on converting binary values to decimal in C, today we're going to follow up with straight-up ports to Perl and shell. Actually, they'll

E4X: JavaScript on Steroids

Saturday, 19 July 2008
IBM Developerworks: "E4X is designed to simplify the task of writing JavaScript code for XML. It is an efficient, powerful tool that you can use to interact with XML nodes and attributes. The primary

Linux 2.6.26 Kernel Benchmarks

Saturday, 19 July 2008
Phoronix: "Over the weekend the Linux 2.6.26 kernel was released. This quarterly update to the Linux kernel introduced Kernel-based Virtual Machine improvements, new One Laptop Per Child support, a ne

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.