#!/usr/bin/python # harness.py - test harness for Cookbook.py library import sys import MySQLdb import Cookbook try: conn = Cookbook.connect() print "Connected" except MySQLdb.Error, e: print "Cannot connect to server" print "Error code:", e.args[0] print "Error message:", e.args[1] sys.exit(1) conn.close() print "Disconnected"
#!/usr/bin/python # placeholder.py - demonstrate statement processing in Python # (with placeholders) import Cookbook import MySQLdb try: conn = Cookbook.connect () except MySQLdb.Error, e: print "Cannot connect to server" print "Error code:", e.args[0] print "Error message:", e.args[1] sys.exit (1) print "Execute INSERT statement using placeholders" try: #@ _EXECUTE_PLACEHOLDER_1_ cursor = conn.cursor () cursor.execute (""" INSERT INTO profile (name,birth,color,foods,cats) VALUES(%s,%s,%s,%s,%s) """, ("De'Mont", "1973-01-12", None, "eggroll", 4)) #@ _EXECUTE_PLACEHOLDER_1_ print "Number of rows inserted: %d" % cursor.rowcount except MySQLdb.Error, e: print "Oops, the statement failed" print e print "Execute SELECT statement using placeholders" try:
CREATE TABLE seqdiag (seq INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY) """) cursor.close () except MySQLdb.Error, e: print "Cannot create seqdiag table" print e.args def gen_seq_val (cursor): try: cursor.execute ("INSERT INTO seqdiag (seq) VALUES(NULL)") except MySQLdb.Error, e: print "Cannot create AUTO_INCREMENT value" print e.args conn = Cookbook.connect () init_table (conn) cursor = conn.cursor () gen_seq_val (cursor) seq = conn.insert_id () print "seq:", seq cursor.execute ("SET @x = LAST_INSERT_ID(99)") seq = conn.insert_id () print "seq after SET via insert_id():", seq cursor.execute ("SELECT LAST_INSERT_ID()") row = cursor.fetchone () seq = row[0] print "seq after SET via LAST_INSERT_ID():", seq