新建mysql01.ini
[database1] host=127.0.0.1 port=3306 user=root passwd=qwer1234 db=data01 charset=utf8
新建mysql01.py
import pymysql import configparser cf =configparser.ConfigParser() cf.read("/Users/syswin/PycharmProjects/pythons/practicesall/mysql01/mysql01.ini") # 连接数据库 host = cf.get("database1","host") port = int(cf.get("database1","port")) """port类型为 int""" user = cf.get("database1","user") passwd = cf.get("database1","passwd") db = cf.get("database1","db") charset = cf.get("database1","charset") print(host) print(port) print(user) print(passwd) print(db) print(charset) connect = pymysql.Connect( host=host, port=port, user=user, passwd=passwd, db=db, charset=charset ) # 获取游标 cursor = connect.cursor() # # 插入数据 # """第一种写法""" # sql_insert = "insert into table01(id,name) values(4,'name04')" # cursor.execute(sql_insert) """第二种写法""" sql_insert = "insert into table01(id,name) values(%d,'%s')" data_insert = (55,'name55') cursor.execute(sql_insert % data_insert) connect.commit() print("成功插入", cursor.rowcount, "条数据") # # 删除数据 sql_delete = "delete from table01 where id = 55" cursor.execute(sql_delete) connect.commit() # 查询数据 sql_select = "select * from table01" cursor.execute(sql_select) # 获取查询结果 result = cursor.fetchall() print(result) print(connect) print(cursor) cursor.close() connect.close()