mysql使用多线程批量插入数据

Thread的start方法被调用时,会自动执行run方法,因此这里需要重写run方法,所有的逻辑程序就放这个run方法里

import pymysql
import threading
def sql_insert():
    conn = pymysql.connect('localhost','root', "shiyi",'dailyfresh')
    cus= conn.cursor()
    #id = int(id)
    try:
        for i in range(1000):
            sql=("INSERT INTO aaa VALUES (0,'%s')")%i
            #tlock.acquire()
            cus.execute(sql)
            conn.commit()
            # print(ok)
            #tlock.release()
    except Exception as e:
        print("one error happen",e)
    finally:
        pass


class myThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        sql_insert()
        # print("开始操作%s"%i)


threads =[]
tlock=threading.Lock()
for  i in range(100):
    thread = myThread()
    threads.append(thread)

for i in range(len(threads)):
    threads[i].start() # Thread的start方法被调用时,会自动执行run方法,因此这里需要重写run方法,这样就会调用这个run方法,所有的逻辑程序就放这个run方法里(targer=指定的函数也是在def run()方法中调用)

targer=指定的函数名也是在Thread类的def run()方法中调用,上面重写了run方法,不需要指定target=

import pymysql
import threading
def sql_insert():
    conn = pymysql.connect('localhost','root', "shiyi",'dailyfresh')
    cus= conn.cursor()
    #id = int(id)
    try:
        for i in range(1000):
            sql=("INSERT INTO aaa VALUES (0,'%s')")%i
            #tlock.acquire()
            cus.execute(sql)
            conn.commit()
            # print(ok)
            #tlock.release()
    except Exception as e:
        print("one error happen",e)
    finally:
        pass
t1=threading.Thread(target=sql_insert)
t1.start()

targer=指定的函数名在Thread类的def run()方法中调用,源码:

def run(self):
    """Method representing the thread's activity.

    You may override this method in a subclass. The standard run() method
    invokes the callable object passed to the object's constructor as the
    target argument, if any, with sequential and keyword arguments taken
    from the args and kwargs arguments, respectively.

    """
    try:
        if self._target:
            self._target(*self._args, **self._kwargs) #开始调用target指定函数名的函数
    finally:
        # Avoid a refcycle if the thread is running a function with
        # an argument that has a member that points to the thread.
        del self._target, self._args, self._kwargs

你可能感兴趣的:(mysql使用多线程批量插入数据)