Python对MySQL的增删改查
通过Python连接MySQL
"""
连接MySQL数据库,并进行增删改查,同时查询了MySQL版本号,并做了动态注册的账号,实现过程:先向userinfo当中添加account、password新字段,接着通过insert插入数据,要注意的是,若是其他字段设置为not null,则必须插入内容。
"""
import pymysql.cursors
# 尝试连接数据库
try:
connect = pymysql.Connect(
host='localhost',
port=3307,
user='root',
password='123456',
db='school',
charset='utf8'
)
print("数据库连接成功")
except pymysql.err.OperationalError as e:
print(f"数据库连接失败: {e}")
创建游标用于解析sql代码
cursor = connect.cursor()
在Python中编写sql语句,并创建userinfo表
其中有ID字段为自动增长、主键、整数,uname字段为字符串、非空,uage字段为整数
sql = """
CREATE TABLE IF NOT EXISTS userinfo(
uid INT PRIMARY KEY AUTO_INCREMENT,
uname VARCHAR(20) NOT NULL,
uage INT
);
"""
cursor.execute(sql)
print("表创建成功")
向表中插入数据
sql2 = "INSERT INTO userinfo(uname, uage) VALUES (%s, %s)"
data1 = ('ann', 18)
data2 = ('alice', 28)
data3 = ('rose', 20)
for data in [data1, data2, data3]:
cursor.execute(sql2, data)
connect.commit()
print('数据插入成功')
更新数据
将年龄为18的同学姓名改为“oi小鬼”
sql3 = "UPDATE userinfo SET uname = %s WHERE uage = %s"
data_update = ('oi小鬼', 18)
cursor.execute(sql3, data_update)
connect.commit()
print('数据修改成功')
查询数据
其中fetchall()用于返回全部数据、fetchone()用于返回查询结果的第一条数据、fetchmany(n)用于返回查询结果的前n条数据。
sql4 = "SELECT * FROM userinfo"
cursor.execute(sql4)
rows = cursor.fetchall()
for row in rows:
print("ID:%s\t姓名:%s\t年龄:%s\t" % (row[0], row[1], row[2]))
查询MySQL数据库版本
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print("MySQL数据库版本是:%s" % version)
最后关闭连接释放资源
cursor.close()
connect.close()
print("数据库连接已关闭")
前后端结合小案例
在制作登录网页时,通常会将用户的注册信息存放在后端数据库MySQL中,当登录时,再通过前端发送请求,请求用户的账号密码进行核对,若是密码输入正确,则登录成功,若是错误则无法成功登录。
下面是基于Python的FLASK框架编写的前后端结合注册页面的小案例,用户输入信息点击注册后,用户数据会存入对应的数据库当中。
项目文件结构
app.py
from flask import Flask, render_template, request, redirect, url_for, flash
import pymysql
app = Flask(__name__)
app.secret_key = 'your_secret_key' # 用于闪现消息
# 数据库配置
db_config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'root',
'db': 'mydb',
'charset': 'utf8'
}
def get_db_connection():
return pymysql.Connect(**db_config)
@app.route('/')
def index():
return render_template('register.html')
@app.route('/register', methods=['POST'])
def register():
uname = request.form['uname']
account = request.form['account']
password = request.form['password']
uage = request.form['uage']
try:
connect = get_db_connection()
cursor = connect.cursor()
# 插入用户信息
sql = "INSERT INTO userinfo (uname, account, password, uage) VALUES (%s, %s, %s, %s)"
cursor.execute(sql, (uname, account, password, uage))
connect.commit()
flash('注册成功!')
except pymysql.err.OperationalError as e:
flash(f"数据库操作出错: {e}")
finally:
cursor.close()
connect.close()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
网页页面register.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
<title>用户注册</title>
</head>
<body>
<div class="container">
<h2>用户注册</h2>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form action="/register" method="POST">
<label for="uname">姓名:</label>
<input type="text" id="uname" name="uname" required>
<label for="account">账号:</label>
<input type="text" id="account" name="account" required>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<label for="uage">年龄:</label>
<input type="number" id="uage" name="uage" required>
<button type="submit">注册</button>
</form>
</div>
</body>
</html>
样式风格styles.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 400px;
margin: auto;
padding: 20px;
background: white;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
label {
display: block;
margin: 10px 0 5px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 10px;
}
button {
width: 100%;
padding: 10px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #218838;
}
.flashes {
list-style-type: none;
padding: 0;
color: red;
}
案例运行
网页效果展示
注册测试
点击注册后:
检查后端数据库中是否已经存在用户的注册信息