python 遍历多线程mysql的所有表格内容并且计算
时间: 2024-02-03 20:13:25 浏览: 113
可以使用Python的`threading`模块和`pymysql`模块实现多线程遍历MySQL表格并计算。
首先,需要连接MySQL数据库,可以使用如下代码:
```python
import pymysql
# 连接MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test')
# 获取游标
cur = conn.cursor()
# 执行SQL语句
cur.execute('SELECT * FROM table_name')
# 获取查询结果
result = cur.fetchall()
# 关闭游标和连接
cur.close()
conn.close()
```
接下来,可以使用`threading`模块创建多个线程并遍历表格。例如:
```python
import threading
import pymysql
# 定义线程类
class MyThread(threading.Thread):
def __init__(self, table_name):
threading.Thread.__init__(self)
self.table_name = table_name
def run(self):
# 连接MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test')
# 获取游标
cur = conn.cursor()
# 执行SQL语句
cur.execute('SELECT * FROM %s' % self.table_name)
# 获取查询结果
result = cur.fetchall()
# 计算结果
total = 0
for row in result:
# 计算每行数据的总和
for i in row:
total += i
print('Table %s Total: %d' % (self.table_name, total))
# 关闭游标和连接
cur.close()
conn.close()
# 获取所有表格名称
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test')
cur = conn.cursor()
cur.execute('SHOW TABLES')
tables = cur.fetchall()
# 创建线程并遍历表格
threads = []
for table in tables:
thread = MyThread(table[0])
threads.append(thread)
thread.start()
# 等待所有线程执行完毕
for thread in threads:
thread.join()
# 关闭游标和连接
cur.close()
conn.close()
```
以上代码可以多线程遍历MySQL数据库的所有表格,并计算每行数据的总和。
阅读全文