文章目录
- 前言
- 目标
- 一、前置条件
- 安装MySQL驱动
- 二、连接mysql
- 初始化连接
- 增加
- 删除
- 改
- 查
- 三、使用及场景
- 参考
前言
渴时一滴如甘露,醉后添杯不如无。
目标
python3连接mysql及crud
一、前置条件
安装MySQL驱动
打开cmd
复制代码
1
2pip install mysqlclient
二、连接mysql
初始化连接
复制代码
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# 引入模块 import MySQLdb # 打开数据库连接 db = MySQLdb.connect( host='127.0.0.1', user='root', passwd='app', port=3306, database='test', charset='utf8') # 使用cursor()方法获取操作游标 cursor = db.cursor() # 使用execute方法执行SQL语句 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取一条数据 data = cursor.fetchone() print(data) # 关闭数据库连接 db.close()
增加
复制代码
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#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打开数据库连接 db = MySQLdb.connect( host='127.0.0.1', user='root', passwd='app', port=3306, database='test', charset='utf8') # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # Rollback in case there is any error db.rollback() # 关闭数据库连接 db.close()
删除
复制代码
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#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打开数据库连接 db = MySQLdb.connect( host='127.0.0.1', user='root', passwd='app', port=3306, database='test', charset='utf8') # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 删除语句 sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20) try: # 执行SQL语句 cursor.execute(sql) # 提交修改 db.commit() except: # 发生错误时回滚 db.rollback() # 关闭数据库连接 db.close()
改
复制代码
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#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打开数据库连接 db = MySQLdb.connect( host='127.0.0.1', user='root', passwd='app', port=3306, database='test', charset='utf8') # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 更新语句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: # 执行SQL语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback() # 关闭数据库连接 db.close()
查
复制代码
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#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打开数据库连接 db = MySQLdb.connect( host='127.0.0.1', user='root', passwd='app', port=3306, database='test', charset='utf8') # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = "select * from tb_item_cat" # 使用execute方法执行SQL语句 cursor.execute(sql) # 使用 fetchone() 方法获取一条数据 data = cursor.fetchone() print(data) # 关闭数据库连接 db.close()
三、使用及场景
数据操作
参考
https://www.runoob.com/python/python-mysql.html
多留言多点赞你们的只支持是我坚持下去的动力,都支棱起来!!!
最后
以上就是正直盼望最近收集整理的关于python3连接mysql适用于个人学习教程前言一、前置条件二、连接mysql三、使用及场景参考的全部内容,更多相关python3连接mysql适用于个人学习教程前言一、前置条件二、连接mysql三、使用及场景参考内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复