python 多線程處理還是很方便
# coding=utf-8
from datetime import datetime
import pymysql.cursors
from faker import Factory
import random
import threading
#假數(shù)據(jù)制造工廠
faker = Factory.create('zh_CN')
def insert_data(threadName,num):
print 'run %s...'%(threadName)
mysql_conn = pymysql.connect(host= '127.0.0.1',
user= 'root',
password= '',
db= 'das',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
with mysql_conn.cursor() as cursor:
for _ in range(0,10):
create_time = faker.date_time_between_dates(datetime(2017,4,10),datetime(2017,5,10))
order_id = random.randint(1,30)
order_status = random.randint(1,5)
sql = "insert into `order` (`order_date_time`,`order_id`,`order_status`) values ('%s','%s','%s')" %(create_time,order_id,order_status)
print sql
cursor.execute(sql)
mysql_conn.commit()
mysql_conn.close()
#定義我的多線程處理
class myThread(threading.Thread):
def __init__(self,name,num):
threading.Thread.__init__(self)
self.name = name
self.num = num
def run(self):
insert_data(self.name,self.num)
#啟動4個線程插入數(shù)據(jù)
threads = []
for i in range(1,5):
name = 'thread-%s' %(i)
new_th = myThread(name,50)
new_th.start()
threads.append(new_th)
for t in threads:
t.join()