Simple MySQL Python Example

Friday, September 21st, 2007

In order to use MySQL with python, you need to get the MySQLdb up and running. Once you have that installed, you use the DB-API to perform queries and such.

The DB-API PEP is good if you already know what you're doing (you can also look at the sqlite module doc). Below is my very simple example. Paul DuBois has an extensive article on using MySQL with python.

from MySQLdb import *

# connect to the database
conn = connect(
	host='localhost',
	user='test',
	db='test'
)

table_def = """
CREATE TABLE samples (
	sample_id int PRIMARY KEY,
	sample_name varchar(20),
	sample_url varchar(250)
)
"""

try:
	cursor = conn.cursor()
	cursor.execute(table_def)
	conn.commit()
except:
	print 'Table already exists.' #obviously, there could be other errors too.

conn.close()
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • del.icio.us
  • Reddit
  • Slashdot
  • Technorati
  • description
  • NewsVine
  • StumbleUpon
  • E-mail this story to a friend!
  • Sphinn

Leave a Reply