Python多线程查询mysql数据库

以下是一个使用 Python 多线程查询 MySQL 数据库的示例代码:

import threading import pymysql class DBThread(threading.Thread): def __init__(self, query): super(DBThread, self).__init__() self.query = query def run(self): conn = pymysql.connect( host='localhost', user='root', password='password', database='testdb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) try: with conn.cursor() as cursor: cursor.execute(self.query) result = cursor.fetchall() print(result) finally: conn.close() def main(): queries = [ 'SELECT * FROM table1', 'SELECT * FROM table2', 'SELECT * FROM table3', 1. ... ] threads = [] for query in queries: thread = DBThread(query) thread.start() threads.append(thread) for thread in threads: thread.join() if __name__ == '__main__': main()