Python操作MySQL

基础使用:

数据插入:

 

练习:

通过Python将数据库student表中的数据以json的格式保存!

from pymysql import Connection

conn = Connection(host='localhost',
                  port=3306,
                  user='root',
                  password='******',  # 自行输入密码
                  autocommit=True)

# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('demo')

cursor.execute("select * from student;")
result: tuple = cursor.fetchall()

f = open("C:/Users/12192/Desktop/demo.txt", 'w', encoding='utf-8')
for each in result:
    init_dict = {"id": each[0], "name": each[1], "age": each[2]}
    f.write(f"{init_dict}")
    f.write("\n")
f.close()
conn.close()

# 检查一下结果
f = open("C:/Users/12192/Desktop/demo.txt", 'r', encoding='utf-8')
print(f.read())
f.close()

 

posted @ 2023-07-31 10:13  Peg_Wu  阅读(3)  评论(0编辑  收藏  举报