[prev in list] [next in list] [prev in thread] [next in thread]
List: python-db-sig
Subject: [DB-SIG] A little example for MySql
From: deirdre () deirdre ! net (Deirdre Saoirse)
Date: 2000-10-19 23:55:36
Message-ID: Pine.LNX.4.10.10010191649040.16861-100000 () rockhopper ! deirdre ! org
[Download RAW message or body]
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
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic