Simple MySQL Python Example

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:
  • Digg
  • del.icio.us
  • Reddit
  • Slashdot
  • Technorati
  • DZone
  • NewsVine
  • StumbleUpon
  • email
  • Sphinn