Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 13 lines
 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()

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

4 comments

Steve Holden 21 years, 11 months ago  # | flag

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

Mark Nenadov (author) 21 years, 11 months ago  # | flag

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

Patrick Paysant 21 years, 5 months ago  # | flag

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.

Reed O'Brien 17 years, 12 months ago  # | flag

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.

Created by Mark Nenadov on Tue, 19 Jun 2001 (PSF)
Python recipes (4591)
Mark Nenadov's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks