ActiveState Code

Recipe 65235: Using the MySQLdb interface


A simple example showing how to use the MySQLdb interface to function with your MySQL database.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import MySQLdb

# Create a connection object and create a cursor
Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="joe", passwd="egf42" db="tst")
Cursor = Con.cursor()

# Make SQL string and execute it
sql = "SELECT * FROM Users"
Cursor.execute(sql)

# Fetch all results from the cursor into a sequence and close the connection
Results = Cursor.fetchall()
Con.close()

Discussion

This is pretty self explanitory. You can get the MySQLdb module from http://sourceforge.net/projects/mysql-python

Comments

  1. 1. At 2:18 p.m. on 2 may 2002, Steve Holden said:

    New Link for Downloads. Note that for up-to-date distributions of MySQLdb you need to go to http://sourceforge.net/projects/mysql-python

  2. 2. At 3:35 p.m. on 12 may 2002, Mark Nenadov (the author) said:

    Thank you! I will update the url so nobody gets mislead.

  3. 3. At 8:29 p.m. on 23 nov 2002, Patrick Paysant said:

    Typo. In order to have the script working, I have to add a comma between passwd and db parameters.

    As here :

    Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="joe", passwd="egf42", db="tst")
    

    Anyway, thanks for this recipe, it help me to start with mysql-python.

  4. 4. At 12:08 p.m. on 28 apr 2006, Reed O'Brien said:

    UNIX Sockets.

    con = MySQLdb.Connect(host='localhost', port=3306, user='user', passwd='secret', db='dbname', unix_socket='/var/lib/mysql/mysql.sock')
    

    sockets are faster on localhost and some distributions of linux keep things in funny places... You can just add the unix_socket parameter like above for Fedora Core 3.

    Maybe named_pipe on windows is similar; I can't say though.

Sign in to comment