#! /usr/bin/env python # -*- coding:utf8 -*- import MySQLdb import sys reload(sys) sys.setdefaultencoding('utf8') # 打开数据库连接 mysqlConn = MySQLdb.connect(host="127.0.0.1",port=3306,user="admin",passwd="123456",db="school",charset="utf8") def mysqlRead(): # 获取操作游标 cursor = mysqlConn.cursor() # sql语句 sql="select * from school.stu" # 执行sql cursor.execute(sql) # # 接收返回的一行数据 # row = cursor.fetchone() # print row # 接收返回的未读取所有行 rs = cursor.fetchall() for row in rs: print row cursor.close() def mysqlInsert(): # 获取操作游标 cursor = mysqlConn.cursor() # sql语句 sql="insert into school.stu(no,name) VALUES ('602','apple2')" try: # 执行sql cursor.execute(sql) # 提交到数据库 mysqlConn.commit() # 操作影响的行数 rowcount = cursor.rowcount print "imfact count:%s" % rowcount except: # 出现异常则回退 mysqlConn.rollback() cursor.close() def main(): mysqlRead() # mysqlInsert() # 关闭连接 mysqlConn.close() if __name__ == "__main__": main()