以下是测试通过的版本。可以换成自己的库,表,实际对比应该不止对比一个表,到时候配置一个列表,逐个轮询。
import concurrent.futures
import pymysql
# 连接数据库的配置
db_config1 = {
'host': '127.0.0.1',
'user': 'kkk',
'password': '',
'db': 'world',
'charset': 'utf8mb4'
}
db_config2 = {
'host': '127.0.0.1',
'user': 'kkk',
'password': 'kkk',
'db': 'mysql',
'charset': 'utf8mb4'
}
# 查询表的数据量
def count_records(db_config, table):
connection = pymysql.connect(**db_config)
with connection.cursor() as cursor:
cursor.execute(f"SELECT COUNT(1) FROM {table}")
count = cursor.fetchone()[0]
connection.close()
return count
# 表1和表2
table1 = 'countrylanguage'
table2 = 'user'
# 使用并行处理进行查询
with concurrent.futures.ThreadPoolExecutor() as executor:
future1 = executor.submit(count_records, db_config1, table1)
future2 = executor.submit(count_records, db_config2, table2)
count1 = future1.result()
count2 = future2.result()
print(f"Table1 {table1} count: {count1}")
print(f"Table2 {table2} count: {count2}")
执行结果如下:
Table1 countrylanguage count: 984
Table2 user count: 5
Process finished with exit code 0
公众号小分享~~~