python3连接MySQL实现增删改查
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实现增删改查的更多相关文章
- Java连接MySQL数据库增删改查通用方法
版权声明:本文为博主原创文章,未经博主允许不得转载. Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类 ...
- jsp-2 简单的servlet连接mysql数据库 增删改查
连接mysql数据库的操作 有增删改查 用的包有 commons-lang3-3.5 mysql-connector-java-5.1.40-bin 但是实际上也就是 数据查询和数据处理两种 所以对数 ...
- java连接mysql以及增删改查操作
java连接数据库的代码基本是固定的,步骤过程觉得繁琐些,代码记起来对我来说是闹挺.直接上代码: (温馨提醒:你的项目提前导入连接数据库的jar包才有的以下操作 ) class DBConnectio ...
- JDBC之Java连接mysql实现增删改查
使用软件:mysql.eclipse 链接步骤: 1.注册驱动 2.创建一个连接对象 3.写sql语句 4.执行sql语句并返回一个结果或者结果集 5.关闭链接(一般就是connection.stat ...
- java连接mysql数据库增删改查操作记录
1. 连接数据库.得到数据库连接变量 注意连接数据库的时候 (1)打开DB Browser 新建一个Database Driver,注意加入Driver JARs的时候加入的包,我的是mysql-co ...
- python3操作mysql数据库增删改查
#!/usr/bin/python3 import pymysql import types db=pymysql.connect("localhost","root&q ...
- 使用MySQL练习增删改查时因为版本问题出现连接错误
使用MySQL练习增删改查时出现连接错误,错误提示如下: 2020-02-19 19:53:51.088 ERROR 16328 --- [reate-249798694] com.alibaba.d ...
- python2.7入门---操作mysql数据库增删改查
Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口.Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: G ...
- python操作mysql数据库增删改查的dbutils实例
python操作mysql数据库增删改查的dbutils实例 # 数据库配置文件 # cat gconf.py #encoding=utf-8 import json # json里面的字典不能用单引 ...
随机推荐
- 交完论文才发现spss数据分析做错了
上周,终于把毕业论文交给导师了.然而,今天导师却邮件我,叫我到他办公室谈谈.具体是谈什么呢?我百思不得其解:对论文几次大修小修后,重复率已经低于学校的上限了,论文结构也很完整,我已经在做答辩的ppt了 ...
- Fire Balls 07——砖块的淡出,消失以及砖塔的下落
版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...
- js 快速排序算法
Array.prototype.quickSort = function() { var len = this.length; if(len < 2) return this; var left ...
- H-Magic Line_2019 牛客暑期多校训练营(第三场)
题目连接: https://ac.nowcoder.com/acm/contest/883/H Description There are always some problems that seem ...
- 2018CCPC 吉林现场赛 赛后总结
一直以来都没有比赛完写总结的习惯,导致前面几次比赛都没有写过总结. 这是我写的第一场总结把,有时间有想法还记得细节的话再把前面几次比赛的总结给补上把. 热身赛: 热身赛的时候,写的比较急想着快点做出题 ...
- hdu 1028 Ignatius and the Princess III 母函数
Ignatius and the Princess III Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K ...
- html/css中相对定位relative和绝对定位absolute的用法
一.相对定位(position:relative) 1.相对定位:将盒子的position属性设置为relative:可通过left.top.right.bottom设置偏移量. 相对定位基础用法示例 ...
- 【Nginx】基于Consul+Upsync+Nginx实现动态负载均衡
一.Http动态负载均衡 什么是动态负载均衡 动态负载均衡实现方案 常用服务器注册与发现框架 二.Consul快速入门 Consul环境搭建 三.nginx-upsync-module nginx-u ...
- 宝塔Linux面板命令
安装宝塔 Centos安装脚本 yum install -y wget && wget -O install.sh http://download.bt.cn/install/inst ...
- JDBC进行批处理Batch
在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率. JDBC实现批处理有两种方式:statement和pr ...