python MySQLdb 库的使用练习
#... python MySQLdb 库的使用 ...
# -*- coding: utf-8 -*-
import MySQLdb
import sys
import 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,create
def 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 False
db.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 results
executeSql("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]