import MySQLdb,time
class mysql_api:
def __init__(self):
self.host = 'localhost'
self.user = 'root'
self.passwd = '123456'
self.charset = 'utf8'
self.db = 'yun'
self.connect()
def connect(self):
self.conn = MySQLdb.connect (host = self.host, user = self.user, passwd = self.passwd,charset=self.charset)
self.conn.select_db(self.db)
self.cursor = self.conn.cursor()
def add(self):
print u'单条插入数据:'
start_time = time.time()
sqli = 'insert into t_ys_tag (tag_name,is_del,create_time) values (%s,%s,%s)'
value = ['xxxxxxxx',0,time.time()]
for i in range(1,50001):
self.cursor.execute(sqli,value)
self.conn.commit()
end_time = time.time()
total_time = end_time -start_time
print '共计时间为:%f秒'% total_time
def addMany(self):
print u'批量插入数据:'
start_time = time.time()
sqli = 'insert into t_ys_tag (tag_name,is_del,create_time) values (%s,%s,%s)'
values = []
for i in range(1,30001):
values.append(('x'+str(i),0,time.time()))
self.cursor.executemany(sqli,values)
self.conn.commit()
end_time = time.time()
total_time = end_time -start_time
print '共计时间为:%f秒'% total_time
def select(self):
print u'当前条数为:'
sqli = "SELECT count(*) FROM `t_ys_tag`"
self.cursor.execute(sqli)
list_admin = self.cursor.fetchall()
if 'list_admin' in locals().keys():
for row in list_admin:
for r in row:
print r
def __del__(self):
self.cursor.close()
self.conn.close()
print u'\n退出实例类'
obj = mysql_api()
obj.select()
obj.add()
obj.select()
obj.addMany()
obj.select()
del obj
python操作数据库类
最新推荐文章于 2024-04-12 16:04:17 发布