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文件

#!/usr/bash/python3
#-*- coding: utf-8 -*-
import pymysql.cursors
'''
想要学习Python?Python学习交流群:1004391443满足你的需求,资料都已经上传群文件,可以自行下载!
'''
#连接MySQL数据库
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123123', db='StudentTest', charset='utf8', cursorclass=pymysql.cursors.DictCursor)

#通过cursor创建游标
cursor = connection.cursor()
# 执行数据查询
sql = "SELECT * FROM `users`;"
cursor.execute(sql)
#查询数据库单条数据
result = cursor.fetchone()
print(result)

print("-----------华丽分割线------------")
# 执行数据查询
sql = "SELECT `id`, `password` FROM `users`"
cursor.execute(sql)

#查询数据库多条数据
result = cursor.fetchall()
for data in result:
  print(data)
# 关闭数据连接
connection.close()

猜你喜欢

转载自blog.csdn.net/qq_40925239/article/details/89971264
今日推荐