MST
星途 面试题库

面试题:Python实现MySQL数据库自动化备份的基础代码编写

请使用Python和相关库(如`mysql - connector - python`)编写一个简单的脚本,实现将MySQL数据库中的某张表数据备份到本地的CSV文件中。假设数据库连接信息为:主机`localhost`,用户名`root`,密码`123456`,数据库名`test_db`,表名为`employees`。
38.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import mysql.connector
import csv

# 连接MySQL数据库
conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='123456',
    database='test_db'
)

cursor = conn.cursor()

# 查询表数据
query = "SELECT * FROM employees"
cursor.execute(query)

# 获取所有数据
data = cursor.fetchall()

# 关闭游标和连接
cursor.close()
conn.close()

# 将数据写入CSV文件
with open('employees_backup.csv', 'w', newline='', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    # 写入表头
    csvwriter.writerow([i[0] for i in cursor.description])
    # 写入数据
    csvwriter.writerows(data)