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增删改查功能都实现了

温馨提示

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

最新文章

  1. Elasticsearch问题总结
  2. windows server 远程连接设置
  3. 对于Eclipse的正确用法
  4. Eclipse 使用maven创建Dynamic Web Project
  5. python核心编程学习记录之函数与函数式编程
  6. List怎么遍历删除元素
  7. Sublime Text 全程指南
  8. 如何在word里面插入目录
  9. 【转】Hbase shell 常用命令
  10. MongoDB 删除数据库
  11. Hdu 1042 N! (高精度数)
  12. Java学习之路(一) —— Java命名规范
  13. 【转】Android Studio 的小小配置
  14. hadoop错误org.apache.hadoop.mapred.MapTask$NewOutputCollector@17bda0f2
  15. C语言第十一次作业--函数嵌套调用
  16. LeetCode &amp; Q121-Best Time to Buy and Sell Stock-Easy
  17. JDBC知识详解
  18. IDEA窗口重置
  19. 【Spark 深入学习 02】- 我是一个凶残的spark
  20. HDU 5069 Harry And Biological Teacher(AC自动机+线段树)

热门文章

  1. 牛客Wannafly挑战赛13-BJxc军训-费马小定理、分式取模、快速幂
  2. light 1205 - Palindromic Numbers(数位dp)
  3. CF - 1110 C Meaningless Operations
  4. CodeM 资格赛 B 可乐 思维
  5. codeforces 361 D. Levko and Array(dp+二分)
  6. Erlang模块ets翻译
  7. java8-Stream原理
  8. Fire Balls 11——平台组合,场景的美化
  9. jps虚拟机进程状态工具
  10. java基本数据类型与引用类型