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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值