python连接mysql数据库

1 import os, sys, string 2 import MySQLdb 3 try: 4 conn = MySQLdb.connect(host='localhost',user='root',passwd='wangmoon',db='hello') 5 except Exception, e: 6 print e 7 sys.exit() 8 cursor = conn.cursor() 9 10 11 sql = "create table if not exists test1(name varchar(128) primary key, age int(4))" 12 try: 13 cursor.execute(sql) 14 except Exception,e: 15 print e; 16 17 sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23) 18 try: 19 cursor.execute(sql) 20 except Exception, e: 21 print e 22 sql = "insert into test1(name, age) values ('%s', %d)" % ("ee", 21) 23 try: 24 cursor.execute(sql) 25 except Exception, e: 26 print e 27 sql = "insert into test1(name, age) values (%s, %s)" 28 val = (("aa", 24), ("bb", 25), ("cc", 26)) 29 try: 30 cursor.executemany(sql, val) 31 except Exception, e: 32 print e 33 sql = "select * from test1" 34 cursor.execute(sql) 35 alldata = cursor.fetchall() 36 if alldata: 37 for rec in alldata: 38 print rec[0], rec[1] 39 cursor.close() 40 conn.close() 41