python3连接MySQL实现增删改查

PyMySQL 安装

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

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

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

$ pip3 install PyMySQL

数据库连接

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

 1  #!/usr/bin/python3
 2 
 3  import pymysql
 4 
 5  # 打开数据库连接
 6  db = pymysql.connect("localhost","root","123456","mydb" )
 7 
 8  # 使用 cursor() 方法创建一个游标对象 cursor
 9  cursor = db.cursor()
10 
11  # 使用 execute()  方法执行 SQL 查询 
12  cursor.execute("SELECT VERSION()")
13 
14  # 使用 fetchone() 方法获取单条数据.
15  data = cursor.fetchone()
16 
17  print ("Database version : %s " % data)
18 
19  # 关闭数据库连接
20  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","123456","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","123456","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","123456","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","123456","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","123456","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增删改查功能都实现了

温馨提示

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

 

 
原文地址:https://www.cnblogs.com/lyxdw/p/9005325.html