sql >> データベース >  >> RDS >> Mysql

PythonマルチスレッドでMySQL接続を処理する方法

    Pythonでマルチスレッド取引mysqlを使用した例を次に示します。テーブルとデータがわからないため、コードを変更するだけで役立つ場合があります。

    import threading
    import time
    import MySQLdb
    
    Num_Of_threads = 5
    
    class myThread(threading.Thread):
    
        def __init__(self, conn, cur, data_to_deal):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.conn = conn
            self.cur = cur
            self.data_to_deal
    
        def run(self):
    
            # add your sql 
            sql = 'insert into table id values ({0});'
            for i in self.data_to_deal:
                self.cur.execute(sql.format(i))
                self.conn.commit()
    
    threads = []
    data_list = [1,2,3,4,5]
    
    for i in range(Num_Of_threads):
        conn = MySQLdb.connect(host='localhost',user='root',passwd='',db='')
        cur = conn.cursor()
        new_thread = myThread(conn, cur, data_list[i])
    
    for th in threads:
        th.start()
    
    for t in threads:
        t.join()
    


    1. MySQL INSERT INTO、IFNOTEXISTの二重条件

    2. ApacheSparkの主キー

    3. DATABASE()–MySQLで現在のデータベース名を取得します

    4. AlwaysOn可用性グループの構成-パート2