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()