[DB-SIG] A little example for MySql
Deirdre Saoirse
deirdre@deirdre.net
Thu, 19 Oct 2000 16:55:36 -0700 (PDT)
I hadn't used the MySql bindings before, so I created a little example
that I thought was clearer than the one included with Andy Dustman's MySql
bindings for python. You may need to change the db, user and pass though.
#!/usr/bin/python
# Written by Deirdre Saoirse Moen, TiVo, Inc.
# Feel free to use for any purpose
import MySQLdb
import traceback
import sys
def tryordie(stmt):
global cursor
try:
cursor.execute(stmt)
except:
print
traceback.print_exc()
mydb.close()
sys.exit()
# begin main program here
try:
mydb = MySQLdb.Connect(db='test', user='foo', passwd='bar')
cursor = mydb.cursor()
except:
print "\n\n"
traceback.print_exc()
sys.exit()
# try and create the table, but if it doesn't exist, don't harf
stmt = "CREATE TABLE COLORS (COLOR varchar(32) DEFAULT '' NOT NULL)"
try:
cursor.execute(stmt)
except:
pass
stmt = "DELETE FROM COLORS"
tryordie(stmt)
stmt = "INSERT INTO COLORS VALUES ('red')"
tryordie(stmt)
stmt = "INSERT INTO COLORS VALUES ('blue')"
tryordie(stmt)
stmt = "INSERT INTO COLORS VALUES ('yellow')"
tryordie(stmt)
# grand finale test
stmt = "select * from COLORS"
tryordie(stmt)
try:
resultSet = cursor.fetchall()
for i in xrange(0, len(resultSet)):
print "Color number",i,"is", resultSet[i][0]
except:
pass
mydb.close()
--
_Deirdre * http://www.sfknit.org * http://www.deirdre.net
"You had thesaurus flakes for breakfast again, didn't you?"
-- Eric Williams