Python Multi-threading Database Connection

In Python, connecting to a database using multiple threads can be done by creating multiple threads using the threading module. Below is a simple example code demonstrating how to connect to a database in multiple threads.

import threading
import pymysql

def connect_database():
    # 连接数据库
    conn = pymysql.connect(host='localhost', user='root', password='password', database='test')
    cursor = conn.cursor()
    
    # 执行SQL查询
    cursor.execute('SELECT * FROM users')
    rows = cursor.fetchall()
    
    # 打印查询结果
    for row in rows:
        print(row)
    
    # 关闭数据库连接
    cursor.close()
    conn.close()

# 创建多个线程
threads = []
for i in range(5):
    thread = threading.Thread(target=connect_database)
    threads.append(thread)

# 启动所有线程
for thread in threads:
    thread.start()

# 等待所有线程结束
for thread in threads:
    thread.join()

In the above code, we create 5 threads using the threading.Thread class, each thread connects to the database and executes a query operation. We then use the start() method to initiate all threads and wait for them to finish using the join() method.

It is important to ensure the thread safety of database connections and query operations when using multi-threaded connections to the database, in order to avoid data races and exceptions. Consider using thread locks or connection pools to ensure thread safety.

bannerAds