PyMySQL 安装

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

PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL。

如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL:

$ pip3 install PyMySQL

数据库连接

通过如下代码测试数据库连接

  #!/usr/bin/python3

  import pymysql

  # 打开数据库连接
db = pymysql.connect("localhost","root","","mydb" ) # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone() print ("Database version : %s " % data) # 关闭数据库连接
db.close()
下面通过实际操作来实现python操作mysql增删改查
创建库ops 添加字段信息 username,email,age,sex
创建服务器server.py
from http.server import HTTPServer, CGIHTTPRequestHandler  

port = 8080  

httpd = HTTPServer((liang, port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()

通过本机ip访问本机服务器

查看本机 ip   linux下 命令行模式下输入ifconfig

打开浏览器输入服务器ip例如127.0.0.1:8080访问

创建html文件index.html 和 add.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul>
<li><a href="/add.html">用户添加</a></li>
<li><a href="/cgi-bin/list.py">用户列表</a></li>
</ul>
</body>
</html> <!--
url http://127.0.0.1:8080/cgi-bin/list.py?a=123&b=345 http://www.baidu.com:80/cgi-bin/list.py 协议: http https ftp file
ip 或 域名
端口: 8080 8090 (80 443)
路径: /cgi-bin/list.py
请求方式:
GET 参数 在url地址后面 以?分割 开始携带参数,多个参数之间用 & 分割
POST -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户添加</title>
</head>
<body>
<form action="/cgi-bin/add.py" method="post">
用户名: <input type="text" name="username"><br>
邮箱: <input type="text" name="email"><br>
年龄: <input type="text" name="age"><br>
性别: <input type="radio" name="sex" value="0">女
<input type="radio" name="sex" value="1">男
<br>
<button>添加</button>
</form>
</body>
</html>

在当前目录创建文件夹cgi-bin

进入文件夹

创建添加操作  add.py   注意如果无权限可以在当前文件夹打开终端 chmod 777 add.py 修改权限

#! /usr/bin/env python3
import cgi,pymysql print('Content-type:text/html;charset=utf-8')
print() # 接受数据
fs = cgi.FieldStorage()
# 根据key接收值
n = fs['username'].value data = {} for x in fs:
# print(x)
# print(fs[x].value)
data[x] = fs[x].value # 打开数据库连接
db = pymysql.connect("127.0.0.1","root","","py9",charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 准备sql语句
sql = 'insert into user(username,email,age,sex) values("{uname}","{uemail}",{uage},{usex})'.format(uname=data['username'],uemail=data['email'],uage=data['age'],usex=data['sex']) # print(sql) try:
# 使用 execute() 方法执行 SQL
cursor.execute(sql)
# 提交执行
db.commit() print('<script>alert("添加成功");location.href="/cgi-bin/list.py";</script>')
except:
# 事务回滚
db.rollback()
print('<script>alert("添加失败");location.href="/add.html";</script>') # 关闭数据库连接
db.close()

创建查看操作文件 list.py

#! /usr/bin/env python3
import cgi,pymysql print('Content-type:text/html;charset=utf-8')
print() # 链接数据库 # 打开数据库连接
# db = pymysql.connect("127.0.0.1","root","123456","ops",charset='utf8', cursorclass=pymysql.cursors.DictCursor)
db = pymysql.connect("127.0.0.1","root","","ops",charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 执行一个查询的语句
sql = 'select * from stu' cursor.execute(sql) # 获取结果 fetchone() 每次获取一条数据
# res = cursor.fetchone() # fecthall() 获取全部结果
res = cursor.fetchall()
# print(res) trs = ''
for x in res:
s = ''
if x[4] == 1:
s = '男'
else:
s = '女' trs += '''
<tr>
<td>{id}</td>
<td>{name}</td>
<td>{email}</td>
<td>{age}</td>
<td>{sex}</td>
<td>
<a href="/cgi-bin/delete.py?id={id}"">删除</a>
<a href="/cgi-bin/edit.py?id={id}">修改</a>
</td>
</tr>
'''.format(id=x[0],name=x[1],email=x[2],age=x[3],sex=s) h = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<center>
<table>
<tr>
<th>ID</th>
<th>用户名</th>
<th>邮箱</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
{}
</table>
</center> </body>
</html> '''.format(trs) print(h) db.close() # 把数据放到html中显示

创建修改  删除  编辑 文件 edit.py

#! /usr/bin/env python3
import cgi,pymysql print('Content-type:text/html;charset=utf-8')
print() # 接受数据
fs = cgi.FieldStorage()
# 接收id
uid = fs['id'].value # 打开数据库连接
db = pymysql.connect("127.0.0.1","root","","ops",charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 准备sql语句
sql = 'select * from stu where id = '+uid # 执行sql语句
cursor.execute(sql) # 获取结果
uinfo = cursor.fetchone() sex = ''
if uinfo[4] == 0:
sex ='''
性别: <input type="radio" name="sex" value="0" checked>女
<input type="radio" name="sex" value="1">男
'''
else:
sex ='''
性别: <input type="radio" name="sex" value="0" >女
<input type="radio" name="sex" value="1" checked>男
''' html = '''
<form action="/cgi-bin/update.py" method="post">
<input type="hidden" name="id" value="{id}" />
用户名: <input type="text" name="username" value="{name}"><br>
邮箱: <input type="text" name="email" value="{email}"><br>
年龄: <input type="text" name="age" value="{age}"><br>
{sex}
<br>
<button>修改</button>
</form>
'''.format(name=uinfo[1],email=uinfo[2],age=uinfo[3],sex=sex,id=uinfo[0]) print(html) # 关闭数据库连接
db.close()

创建修改操作 文件 update.py

#! /usr/bin/env python3
import cgi,pymysql print('Content-type:text/html;charset=utf-8')
print() # 接受数据
fs = cgi.FieldStorage() data = {} for x in fs:
# print(x)
# print(fs[x].value)
data[x] = fs[x].value # print(data) # 打开数据库连接
db = pymysql.connect("127.0.0.1","root","","ops",charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 准备sql语句
sql = 'update stu set name="'+data['username']+'",email="'+data['email']+'",age='+data['age']+',sex='+data['sex']+' where id = '+data['id'] # print(sql) try:
# 使用 execute() 方法执行 SQL
cursor.execute(sql)
# 提交执行
db.commit() print('<script>alert("修改成功");location.href="/cgi-bin/list.py";</script>')
except:
# 事务回滚
db.rollback()
print('<script>alert("修改失败");location.href="/cgi-bin/list.py";</script>') # 关闭数据库连接
db.close()
创建删除操作文件 delete.py
#! /usr/bin/env python3
import cgi,pymysql print('Content-type:text/html;charset=utf-8')
print() # 接受数据
fs = cgi.FieldStorage() uid = fs['id'].value # print(uid) # 打开数据库连接
db = pymysql.connect("127.0.0.1","root","","ops",charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 准备sql语句
sql = 'delete from stu where id='+uid # print(sql) try:
# 使用 execute() 方法执行 SQL
cursor.execute(sql)
# 提交执行
db.commit() print('<script>alert("删除成功");location.href="/cgi-bin/list.py";</script>')
except:
# 事务回滚
db.rollback()
print('<script>alert("删除失败");location.href="/cgi-bin/list.py";</script>') # 关闭数据库连接
db.close()u

到这一步,python操作mysql增删改查功能都实现了

温馨提示

  • 如果您对本文有疑问,请在评论部分留言,我会在最短时间回复。
  • 如果本文帮助了您,也请评论关注,作为对我的一份鼓励。
  • 如果您感觉我写的有问题,也请批评指正,我会尽量修改。
  • 本文为原创,转载请注明出处。
 

python3连接MySQL实现增删改查的更多相关文章

  1. Java连接MySQL数据库增删改查通用方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类 ...

  2. jsp-2 简单的servlet连接mysql数据库 增删改查

    连接mysql数据库的操作 有增删改查 用的包有 commons-lang3-3.5 mysql-connector-java-5.1.40-bin 但是实际上也就是 数据查询和数据处理两种 所以对数 ...

  3. java连接mysql以及增删改查操作

    java连接数据库的代码基本是固定的,步骤过程觉得繁琐些,代码记起来对我来说是闹挺.直接上代码: (温馨提醒:你的项目提前导入连接数据库的jar包才有的以下操作 ) class DBConnectio ...

  4. JDBC之Java连接mysql实现增删改查

    使用软件:mysql.eclipse 链接步骤: 1.注册驱动 2.创建一个连接对象 3.写sql语句 4.执行sql语句并返回一个结果或者结果集 5.关闭链接(一般就是connection.stat ...

  5. java连接mysql数据库增删改查操作记录

    1. 连接数据库.得到数据库连接变量 注意连接数据库的时候 (1)打开DB Browser 新建一个Database Driver,注意加入Driver JARs的时候加入的包,我的是mysql-co ...

  6. python3操作mysql数据库增删改查

    #!/usr/bin/python3 import pymysql import types db=pymysql.connect("localhost","root&q ...

  7. 使用MySQL练习增删改查时因为版本问题出现连接错误

    使用MySQL练习增删改查时出现连接错误,错误提示如下: 2020-02-19 19:53:51.088 ERROR 16328 --- [reate-249798694] com.alibaba.d ...

  8. python2.7入门---操作mysql数据库增删改查

    Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口.Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: G ...

  9. python操作mysql数据库增删改查的dbutils实例

    python操作mysql数据库增删改查的dbutils实例 # 数据库配置文件 # cat gconf.py #encoding=utf-8 import json # json里面的字典不能用单引 ...

随机推荐

  1. crontab使用方法

    一.crontab基本用法 1.1 cron服务 cron是一个linux下 的定时执行工具,可以在无需人工干预的情况下运行作业. service crond start //启动服务 service ...

  2. C#开发BIMFACE系列10 服务端API之获取文件下载链接

    系列目录     [已更新最新开发文章,点击查看详细] 通过BIMFACE控制台或者调用服务接口上传文件成功后,默认场景下需要下载该源文件,下载文件一般需要知道文件的下载链接即可.BIMACE平台提供 ...

  3. NLP(十八) 一维卷积网络IMDB情感分析

    准备 Keras的IMDB数据集,包含一个词集和对应的情感标签 import pandas as pd from keras.preprocessing import sequence from ke ...

  4. cogs 313. [POI2001] 和平委员会(2-SAT

    http://cogs.pro:8080/cogs/problem/problem.php?pid=pyzQimjkj 题意:有n个集合,每个集合有俩元素,要从n个中各选一个放一堆,但是有的俩不能同时 ...

  5. CF1025B Weakened Common Divisor 数学

    Weakened Common Divisor time limit per test 1.5 seconds memory limit per test 256 megabytes input st ...

  6. 线段树模板 hdu 1166 敌兵布阵

    敌兵布阵 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submis ...

  7. Spring Cloud官方文档中文版-Spring Cloud Config(上)-服务端(配置中心)

    官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#spring-cloud-feign 文中例子我做了一些测试在:http ...

  8. Qt之键盘事件监听-实时响应大小写Capslock按键

    目录 一.开篇 二.效果展示 三.实现思路 1.重写QLlinEdit 2.全局应用程序事件 3.windows钩子 四.相关文章 原文链接:Qt之键盘事件监听-实时响应大小写Capslock按键 一 ...

  9. 【第十三篇】mvc下载文件,包括配置xml保护服务端文件不被外链直接访问

    这里先说下载文件 <a style="color:black; margin-right:3px;" onclick="dowAtt(' + index + ')& ...

  10. Spring Boot 利用 nginx 实现生产环境的伪热更新

    当我们在服务器部署Java程序,特别是使用了 Spring Boot 生成单一 Jar 文件部署的时候,单一文件为我们开发单来的极大的便利性,保障程序的完整性.但同时对我们修改程序中的任何一处都带来重 ...