python 读取mysql数据库的每一张表格,给每张表格增加两列,列名称为a和b,数据类型为小数.,如果a和b列存在则跳过,并且使用多线程
时间: 2023-12-19 14:06:49 浏览: 17
可以使用 Python 中的 `multiprocessing` 模块来实现多线程,`pymysql` 库用于连接 MySQL 数据库进行操作。
以下是示例代码:
```python
import pymysql
from multiprocessing.pool import ThreadPool
# MySQL 数据库连接信息
host = "localhost"
user = "root"
password = "password"
database = "test"
def get_tables():
"""
获取数据库中的所有表格
"""
conn = pymysql.connect(host=host, user=user, password=password, database=database)
cursor = conn.cursor()
cursor.execute("show tables")
tables = [t[0] for t in cursor.fetchall()]
cursor.close()
conn.close()
return tables
def add_columns(table):
"""
给指定表格添加 a 和 b 列
"""
conn = pymysql.connect(host=host, user=user, password=password, database=database)
cursor = conn.cursor()
cursor.execute("desc {}".format(table))
columns = [c[0] for c in cursor.fetchall()]
# 如果 a 和 b 列已存在,则跳过
if "a" in columns and "b" in columns:
cursor.close()
conn.close()
return
# 添加 a 和 b 列
cursor.execute("alter table {} add column a decimal(10,2), add column b decimal(10,2)".format(table))
conn.commit()
cursor.close()
conn.close()
if __name__ == '__main__':
tables = get_tables()
pool = ThreadPool(processes=4) # 设置线程数为 4
pool.map(add_columns, tables) # 对每个表格进行添加列操作
pool.close()
pool.join()
```
上述代码中,使用 `get_tables` 函数获取数据库中的所有表格,然后使用 `add_columns` 函数给每个表格添加 a 和 b 两列。在 `add_columns` 函数中,首先获取表格的所有列名,如果 a 和 b 列已存在,则跳过,否则使用 SQL 语句添加 a 和 b 列。最后,使用多线程的方式对每个表格进行添加列的操作。