转载请注明出处❤️

作者:IT小学生蔡坨坨

原文链接:https://www.caituotuo.top/6bf90683.html


0. 什么是PyMySQL

1. 安装PyMySQL

1
pip3 install PyMySQL

2. 创建、查看、删除、使用数据库

(1)创建数据库
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
# -*- coding:utf-8 -*-
# 作者:IT小学生蔡坨坨
# 时间:2022/2/26 14:07
# 功能:Python+PyMysql创建数据库

# 安装并导入pymysql(pip3 install PyMySQL)
import pymysql

# 创建连接
db_conn = pymysql.connect(host='localhost', # 地址
user='root', # 用户名
password='root', # 密码
charset='utf8' # 编码格式
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db_conn.cursor()

# 创建数据库的sql语句,若数据库已存在就不创建
sql = "CREATE DATABASE IF NOT EXISTS caituotuo_db"

# 使用 execute() 方法执行SQL创建数据库
cursor.execute(sql)

# 创建完成提示
print("Done!")

通过Navicat工具可以看到我们刚创建完成的数据库caituotuo_db

(2)查询数据库
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- coding:utf-8 -*-
# 作者:IT小学生蔡坨坨
# 时间:2022/2/26 14:53
# 功能:查询所有数据库并打印

import pymysql

# 创建连接 和 游标对象cursor
db_conn = pymysql.connect(host='localhost',
user='root',
password='root',
charset='utf8')
cursor = db_conn.cursor()

# 查询所有数据库的SQL语句
sql = "SHOW DATABASES"

# 执行SQL,返回数据库总数量
databases_num = cursor.execute(sql)
print("数据库总数:" + str(databases_num) + " 个") # 输出数据库总数

# fetchall()方法 返回多个元组,即返回多个记录(rows),如果没有结果,则返回 ()
result = cursor.fetchall()
print(result) # (('information_schema',), ……('test',))

print("数据库列表:")
for i in result:
# print(i)
for j in i:
print(j)
"""
数据库列表:
information_schema
bcbx_chs
caituotuo_db
chstracer
listudy
mysql
performance_schema
test
"""

print("打印成一行,空格隔开:", end="")
for i in result:
for j in i:
# 打印成一行,空格隔开
print(j, end=' ')
# 打印成一行,空格隔开:information_schema bcbx_chs caituotuo_db chstracer listudy mysql performance_schema test

# 关闭连接
db_conn.close()

3. 创建、查看、使用、删除数据表

4. 数据表的增删改查

未完待续……