python MySQLdb 库的使用练习

来源:互联网 发布:mac ps没有足够内存 编辑:程序博客网 时间:2024/06/06 05:57
python MySQLdb 库的使用练习
#... python MySQLdb 库的使用 ...# -*- coding: utf-8 -*-import MySQLdbimport sysimport time#是否开启日志 1表示开启 0 表示不开启logDebug = 1##输出日志到文件def writeLog(data):if logDebug == 1:nowtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))fo = open("/tmp/mypy.log", "a")strdata = repr(data);logdata = "%s:%s\n" %(nowtime,strdata)fo.write(logdata)fo.close()#执行sql语句,用于insert,del,update,createdef executeSql(insertSql):db = MySQLdb.connect("localhost","root","cxst789","zkdb")cursor = db.cursor()cursor.execute('SET NAMES UTF8')  try:cursor.execute(insertSql)db.commit()except:db.rollback()db.close()retun Falsedb.close()return True#执行查询语句def getAllSql(sql):db = MySQLdb.connect("localhost","root","cxst789","zkdb")cursor = db.cursor()cursor.execute('SET NAMES UTF8')  cursor.execute(sql)results = cursor.fetchall()db.close()return resultsexecuteSql("INSERT INTO `user` SET user='bai',password='123456',name='小白';")sql = "SELECT `user`,`name` FROM `user`;"writeLog(sql)res = getAllSql(sql)writeLog(res)for row in res:writeLog(row)print row[0],row[1]

原创粉丝点击