介绍
由于 MySQLdb 模块还不支持 Python3.x,所以 Python3.x 如果想连接MySQL需要安装 pymysql 模块。
安装
1、pip安装
pip3 install PyMySQL
2、pycharm安装
安装过程
[File] > [settings] > [Project: 项目文件名] > [Project Interpreter] > [Install按钮]
下载安装
使用方法
pymysql.Connect()参数说明
参数 | 解释 |
---|---|
host(str) | MySQL服务器地址 |
port(int) | MySQL服务器端口号 |
user(str) | 用户名 |
passwd(str) | 密码 |
db(str) | 数据库名称 |
charset(str) | 连接编码 |
connection对象支持的方法
方法 | 解释 |
---|---|
cursor() | 使用该连接创建并返回游标 |
commit() | 提交当前事务 |
rollback() | 回滚当前事务 |
close() | 关闭连接 |
cursor对象支持的方法
方法 | 解释 |
---|---|
execute(op) | 执行一个数据库的查询命令 |
fetchone() | 取得结果集的下一行 |
fetchmany(size) | 获取结果集的下几行 |
fetchall() | 获取结果集中的所有行 |
rowcount() | 返回数据条数或影响行数 |
close() | 关闭游标对象 |
使用示例
此代码仅为示例,直接复制粘贴运行会报错,因为代码不变的情况下可能存在重复建表等语法错误
E导入模块
import pymysql
# 创建连接
connect = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='fei')
# 创建游标
cursor = connect.cursor()
#创建数据库表
data = ("create table PpQ("
"id int primary key auto_increment,"
"time datetime,"
"my_thing varchar(177))charset=utf8; ")
#插入数据
sql_insert = ("insert into PpQ(time,my_thing) values ('2019-05-13 07:32:10','smile')")
#读取数据
cursor.execute("select * from ppq")
try:
#执行数据库查询命令
cursor.execute(data)
cursor.execute(sql_insert)
print("数据库语法操作正常。。。")
except:
print("您的语法存在错误")
# 获取第一行数据
row_1 = cursor.fetchone()
print(row_1)
# 获取前n行数据
row_2 = cursor.fetchmany(3)
print(row_2)
# 获取所有数据
row_3 = cursor.fetchall()
print(row_3)
connect.commit() # 连接提交
cursor.close() # 关闭游标
connect.close() # 关闭连接