现在的位置: 首页 > 综合 > 正文

python连接mysql数据库

2012年11月14日 ⁄ 综合 ⁄ 共 842字 ⁄ 字号 评论关闭
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

【上篇】
【下篇】

抱歉!评论已关闭.