#encoding=utf-8
import pymysql
import random
import time
class OpeateMysql:
#初始化类
def __init__(self, ty):
self.type = ty
self.coon = None
self.listsql = []
pass
#连接数据库
def connectSql(self, ip, port, dbname, user=None, pwd = None,):
if self.type == 'mysql':
self.coon = pymysql.connect(
host=ip,
user=user,
passwd=pwd,
port=port,
db=dbname,
charset='utf8'
)
return True
#关闭连接
def disConnct(self):
self.coon.close()
#添加sql语句
def appendSql(self, sql):
if sql is not None:
self.listsql.append(sql)
#执行SQL
def excuteInsertAll(self):
try:
cur = self.coon.cursor()
for sql in self.listsql:
cur.execute(sql)
self.coon.commit()
cur.close()
except Exception:
print('发生异常',Exception)
self.coon.rollback()
#生成数据SQL小工厂
def defineSql(ope,count):
for i in range(count):
core = random.choice(['yuwen', 'shuxue', 'yingyu'])
grade = random.randint(59, 100)
name = ''.join(random.sample(['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'], 10))
sql = "insert into student values(null,'"+ name + "','"+ core +"',"+ str(grade) +");"
ope.appendSql(sql)
#主函数
if __name__ == '__main__':
print('hello world!!')
ope = OpeateMysql('mysql')
cobl = ope.connectSql('192.168.0.100', 3306, 'newtest', 'root', '123456')
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
defineSql(ope,10000)
print()
ope.excuteInsertAll()
ope.disConnct()
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) #用来检查性能