Connect to a MySQL database in Python
import MySQLdb as mysqlib
import sys
 
dbserver = "localhost"
dbuser = "username"
dbpass = "********"
db = "dbname"
conn = None
 
try:
	conn = mysqlib.connect(dbserver, dbuser, dbpass, db);
	print "Connected!n"
 
	cursor = conn.cursor()
	cursor.execute("SELECT * from datatable")
 
	results = cursor.fetchall()
 
	for record in results:
		print record[0] , ", ", record[1]
 
except mysqlib.Error, e:
	print "Error %d: %s" % (e.args[0], e.args[1])
	sys.exit(1)
finally:
	if conn:
		conn.close()
Categories: MySQL, Python Tags: , , ,
%d bloggers like this: