首页 > 代码库 > python访问数据库一
python访问数据库一
直接访问mysql,示例如下:
# coding:utf-8import timeimport MySQLdb# import traceback# import sysconn = MySQLdb.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘root‘, db=‘dev‘, charset="utf8", )cur = conn.cursor()# cur.execute("SET NAMES utf8")try: sql = "create table mytest1(" sql = sql + "id int(11) not null auto_increment," sql = sql + "channelcode varchar(100) null," sql = sql + "systemcode varchar(100) not null," sql = sql + "systemname varchar(100) not null," sql = sql + "primary key(id))" print sql; cur.execute(sql);except Exception, e: print Exception, ":", etry: cur.execute("insert into mytest1(systemcode,systemname) values(‘test‘,‘测试‘)") conn.commit() print ‘insert new mytest1.‘except Exception, e: print Exception, ":", e # traceback.print_exc()# except:# info=sys.exc_info()# print info[0],":",info[1]try: cur.execute("update mytest1 set systemname=‘测试" + time.strftime(‘%Y-%m-%d %H:%M:%S‘) + "‘ where systemcode=‘test‘"); conn.commit()except Exception, e: print Exception, ":", etry: itsystem = cur.execute("select * from mytest1"); print ‘count:‘ + str(itsystem); info = cur.fetchmany(itsystem) for ii in info: # if print ii,chinese string will print it‘s unicode with u\#### print str(ii[0]) + ‘,‘ + (ii[1] == None and str(None) or ii[1]) + ‘,‘ + ii[2] + ‘,‘ + ii[3]except Exception, e: print Exception, ":", etry: cur.execute("delete from itsystem where systemcode=‘test‘"); conn.commit() cur.execute("drop table mytest1");except Exception, e: print Exception, ":", ecur.close()conn.close()
python访问数据库一
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。