import pymysql
# 连接到数据库
conn = pymysql.connect(
host='your_host', # 你的MySQL主机
user='your_user', # 你的MySQL用户名
password='your_password', # 你的MySQL密码
database='your_database' # 你的数据库名
)
# 创建一个游标对象
cursor = conn.cursor()
# 执行操作
try:
# 复制表结构
cursor.execute('CREATE TABLE ht_change_records_0_distinct LIKE ht_change_records_0')
# 添加索引
cursor.execute('ALTER TABLE ht_change_records_0_distinct ADD PRIMARY KEY (u_id), ADD INDEX (eid)')
# 复制数据
cursor.execute('INSERT INTO ht_change_records_0_distinct SELECT * FROM ht_change_records_0 GROUP BY u_id')
# 提交更改
conn.commit()
except Exception as e:
print(f"发生错误:{e}")
# 如果发生错误,则回滚更改
conn.rollback()
# 关闭游标和连接
cursor.close()
conn.close()