python3连接mysql数据库 PyMySQL

一、安装PyMySQL驱动 Python3

使用 PyMySQL 连接数据库,并实现简单的增删改查

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。

PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL。 如果还未安装,我们可以使用以下命令安装最新版的

PyMySQL: $ pip3 install PyMySQL

二、python数据库连接

1、打开mysql 数据库

mysql -uroot -p

mysql> create database StudentTest set charset = 'utf8';

Query OK, 1 row affected (0.00 sec)

mysql> use StudentTest

2、创建表

1 mysql> CREATE TABLE `users`
2 ( `id` INT(11) NOT NULL AUTO_INCREMENT,
3 `email` VARCHAR(255) COLLATE utf8_bin NOT NULL,
4 `password` VARCHAR(255) COLLATE utf8_bin NOT NULL,
5 PRIMARY KEY (`id`) ENGINE=INNODB
6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

3、添加数据

INSERT INTO `StudentTest`.`users` (`email`, `password`) VALUES ('12', '345');

INSERT INTO `StudentTest`.`users` (`email`, `password`) VALUES ('45', '456');

4、创建一个python文件

 1 #!/usr/bash/python3
 2 #-*- coding: utf-8 -*-
 3 import pymysql.cursors
 4 
 5 #连接MySQL数据库
 6 connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123123', db='StudentTest', charset='utf8', cursorclass=pymysql.cursors.DictCursor)
 7 
 8 #通过cursor创建游标
 9 cursor = connection.cursor()
10 # 执行数据查询
11 sql = "SELECT * FROM `users`;"
12 cursor.execute(sql)
13 #查询数据库单条数据
14 result = cursor.fetchone()
15 print(result)
16 
17 print("-----------华丽分割线------------")
18 # 执行数据查询
19 sql = "SELECT `id`, `password` FROM `users`"
20 cursor.execute(sql)
21 
22 #查询数据库多条数据
23 result = cursor.fetchall()
24 for data in result:
25   print(data)
26 # 关闭数据连接
27 connection.close()

执行就可以查看到结果