发布于 

Pythons连接mysql数据库

前言

首先我们前提主机主机要有mysql数据库,然后要使我们的python连接到数据库,我们需要使用pymysql这个库所以我们需要安装

1.安装Mysql

首先我们先前往官网下载mysql

1
https://dev.mysql.com/downloads/mysql/

注意⚠️:
在configuration这一项时,我们选择Use Legacy Password Encryption,然后设置我们的mysql的root用户密码

当我们看到左边有两个绿点就代表安装好了
mac安装完后我们在终端输入mysql,测试是否环境配置好了

1
2
3
$ mysql


如果出现 zsh: command not found: mysql
这说明我们还没有配置环境,在终端通过 vim 来编辑 .zshrc 配置文件

1
$ sudo vim ~/.zshrc

点击 i 键,进入编辑模式,在配置文件中添加如下路径:

1
export PATH=$PATH:/usr/local/mysql/bin

然后按 esc 退出编辑模式,输入 :wq 保存退出

接着在终端执行 source ~/.zshrc 使配置生效

1
$ source ~/.zshrc

windows用户则请找找关于windows安装mysql的教程

安装pymysql库

接下来我们开始用python来对mysql进行操作
首先我们先来安装pymysql库
在我们安装完python后,会自带一个pip工具
我们在终端中输入命令

1
pip install pymysql

就可以安装了,等待安装完

导入pymysql库

1
from pymysql import Connection

连接mysql

1
2
3
4
5
6
conn = Connection(
host = '主机名(ip)',
port = 端口(默认3306),
user = '用户名(默认root)',
password = '用户密码',
)

# 获取游标对象

1
cursor = conn.cursor()

选择数据库

1
conn.select_db('数据库名')

执行sql命令

1
cursor.execute("这里是sql命令")

注意的是如果是查询,我们需要用fetchall()方法来获取一个嵌套元组,元组中的每个元素都是一个元组,这个元组中存放的是每一行的内容(记录)
如果执行的是插入语句,则我们需要在插入语句的下面添加代表确认插入的语句,通过使用commit()方法
例子:
1、查询

1
2
3
4
cursor.execute("select * from student")
results: tuple = cursor.fetchall()
for r in results:
print(r)

2、插入

1
2
cursor.execute("insert into student values(1001,'hhh',32)")
conn.commit() #

关闭数据库

要关闭数据库我们使用close()方法

1
conn.close()

如果我们需要自动确认,则需要在Connection中添加autocommit=True

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# install pymysql
# 导入pymysql
from pymysql import Connection
# mysql数据库的连接
conn = Connection(
host = 'localhost', # 主机名(ip)
port = 3306, # 端口
user = 'root', # 用户名
password = '123456', #密码
# autocommit=True # 自动提交
)

# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('test')
# 使用游标对象,执行sql语句
# cursor.execute("create table test_1(id int)")

# 查询
#cursor.execute("select * from student")
#results: tuple = cursor.fetchall()
#for r in results:
# print(r)

# 数据插入
cursor.execute("insert into student values(1001,'hhh',32)")
# 提交手动确认(事物)
conn.commit()
# 关闭数据库
conn.close()

大家可以根据sql语句来对数据库执行操作,当然在我的博客中也有关于sql语句的操作举例