python 按照时间序列读取mysql每一张表的数据
时间: 2023-12-03 14:44:47 浏览: 47
可以通过在Python中使用MySQL Connector来连接到MySQL数据库并按照时间序列读取每张表的数据。以下是一个示例代码:
```python
import mysql.connector
from mysql.connector import Error
# 连接到MySQL数据库
try:
connection = mysql.connector.connect(host='localhost',
database='mydatabase',
user='myusername',
password='mypassword')
if connection.is_connected():
db_Info = connection.get_server_info()
print("连接到 MySQL 数据库版本:", db_Info)
# 获取数据库中所有表的名称和创建时间
cursor = connection.cursor()
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
table_info = {}
for table in tables:
cursor.execute(f"SHOW CREATE TABLE {table[0]}")
create_table = cursor.fetchone()[1]
table_info[table[0]] = create_table.split('\n')[1].strip()
# 按照创建时间排序表名
sorted_tables = sorted(table_info.items(), key=lambda x: x[1])
# 读取每张表的数据
for table in sorted_tables:
cursor.execute(f"SELECT * FROM {table[0]}")
rows = cursor.fetchall()
for row in rows:
print(row)
except Error as e:
print("连接失败:", e)
finally:
# 关闭数据库连接
if (connection.is_connected()):
cursor.close()
connection.close()
print("连接已关闭")
```
该代码首先连接到MySQL数据库,然后获取数据库中所有表的名称和创建时间。接下来,它按照创建时间排序表名,并依次读取每张表的数据。最后,关闭数据库连接。
请注意,该代码仅为示例代码,实际应用中可能需要根据具体情况进行修改。