Posts Tagged ‘py’

Simple Example Usage of MySQLdb with Python

Thursday, June 18th, 2009

MySQLdb is a set of open source Python libraries that allow you to interact with MySQL databases at a higher level than the traditional C API methods.

Here is some code that takes two command line arguments, and stuffs them into a table as contents of the fields “ID” and “INPUT”.  (in other words it is a simple database of ID numbers and text).

#!/usr/bin/env python
#
# example of taking data from Python variables and inserting them into a database.
import MySQLdb, sys

id = sys.argv[1]
input = sys.argv[2] 

sql = "INSERT INTO your_table_name (id, input) VALUES("
sql += id
sql += ", '"
sql += input
sql += "')"

db = MySQLdb.connect(host="yourhost" db="yourdb", user="username", passwd="password" )
dbc = db.cursor()
dbc.execute(sql)

It’s JUST THAT EASY! :D