pip install PyMySQL
安装成功截图
2、 *** 作示例(1)创建表test
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
(2)示例代码
# coding:utf-8
import pymysql
#1、打开数据库连接
db = pymysql.connect("localhost","root","root","file")
#2、使用cursor()获取 *** 作游标
cursor = db.cursor()
#3、增删改查sql,例如插入一条数据
sql = "insert into test (name) value ('python01')"
#4、执行sql
cursor.execute(sql)
#5、提交到数据库执行
db.commit()
#6、关闭连接
db.close()
(3)运行后发现报错
(4)查看pymysql.connect()方法底层源码发现前四个参数基于DB-API 2.0建议。
(5)解决方法:
db = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="file")
(6)数据库成功插入数据
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)