4.Python-用Python,Ajax实现MySQL数据库的新增数据

题记

用python,ajax实现mysql数据库的新增数据。以下是一个简单的实例和操作过程。

安装flask模块

pip install flask

安装mysql.connector模块

pip install mysql-connector-python

编写app.py文件

app.py文件如下:

块引用可能显示不完整,下面附加了全部代码

复制代码
from flask import Flask, request, render_template
import mysql.connector

app = Flask(__name__)

# 连接到MySQL数据库
db = mysql.connector.connect(
    host="localhost",
    user="root",
    password="123456",
    database="test"
)

# 创建游标对象
cursor = db.cursor()

# 创建表格(如果不存在)
cursor.execute("CREATE TABLE IF NOT EXISTS students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")

@app.route('/')
def index():
    return render_template('index111.html')

@app.route('/add', methods=['POST'])
def add():
    name = request.form['name']
    age = request.form['age']

    # 向数据库插入数据
    sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
    values = (name, age)
    cursor.execute(sql, values)
    db.commit()

    return "数据已成功添加到数据库!"

if __name__ == '__main__':
    app.run()
python 复制代码
from flask import Flask, request, render_template
import mysql.connector

app = Flask(__name__)

# 连接到MySQL数据库
db = mysql.connector.connect(
    host="localhost",
    user="root",
    password="123456",
    database="test"
)

# 创建游标对象
cursor = db.cursor()

# 创建表格(如果不存在)
cursor.execute("CREATE TABLE IF NOT EXISTS students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/add', methods=['POST'])
def add():
    name = request.form['name']
    age = request.form['age']

    # 向数据库插入数据
    sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
    values = (name, age)
    cursor.execute(sql, values)
    db.commit()

    return "数据已成功添加到数据库!"

if __name__ == '__main__':
    app.run()

编写index.html文件

注意:index.html需要放在templates文件夹下,否则服务器会找不到文件

index.html文件如下:

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Add Student</title>
<!--引用jquery-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <!--创建表单id-->
    <form id="updateForm">
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name"><br><br>
    <label for="age">年龄:</label>
    <input type="text" id="age" name="age"><br><br>
    <input type="submit" value="Add">
    </form>

<script>
    // 使用jQuery库来处理表单的提交行为,并使用Ajax方式将表单数据发送到服务器进行处理
    // $ 是一个函数名(或别名)
    // 它相当于原生js中的 document.querySelector 或 document.querySelectorAll 选择器方法。
    // $(document).ready()方法,它会在文档加载完成后执行其中的代码
    $(document).ready(function() {
        // $("#updateForm").submit(function(event) { ... });
        // 这是通过选择器选中id为"updateForm"的表单元素,并使用.submit()方法来监听表单的提交事件。
        // 当表单提交时,会执行其中的回调函数。
        $("#updateForm").submit(function(event) {
            event.preventDefault(); // 阻止表单默认提交行为,从而避免页面刷新。
            //通过选择器选中id为"name"和"age"的输入框元素,并使用.val()方法获取输入框的值。
            var name = $("#name").val();
            var age = $("#age").val();
            //$.ajax({ ... });
            // 使用jQuery的.ajax()方法来发送Ajax请求。在其中设置了请求的URL、HTTP方法和数据
            $.ajax({
                url: "/add",
                method: "POST",
                data: { name: name, age: age },
                // success: function(response) { ... }
                // 这是在Ajax请求成功后的回调函数
                success: function(response) {
                    // 在这里处理Ajax响应
                    console.log(response);
                }
            });
        });
    });
</script>
</body>
</html>
html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Add Student</title>
<!--引用jquery-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <!--创建表单id-->
    <form id="updateForm">
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name"><br><br>
    <label for="age">年龄:</label>
    <input type="text" id="age" name="age"><br><br>
    <input type="submit" value="Add">
    </form>

<script>
    // 使用jQuery库来处理表单的提交行为,并使用Ajax方式将表单数据发送到服务器进行处理
    // $ 是一个函数名(或别名)
    // 它相当于原生js中的 document.querySelector 或 document.querySelectorAll 选择器方法。
    // $(document).ready()方法,它会在文档加载完成后执行其中的代码
    $(document).ready(function() {
        // $("#updateForm").submit(function(event) { ... });
        // 这是通过选择器选中id为"updateForm"的表单元素,并使用.submit()方法来监听表单的提交事件。
        // 当表单提交时,会执行其中的回调函数。
        $("#updateForm").submit(function(event) {
            event.preventDefault(); // 阻止表单默认提交行为,从而避免页面刷新。
            //通过选择器选中id为"name"和"age"的输入框元素,并使用.val()方法获取输入框的值。
            var name = $("#name").val();
            var age = $("#age").val();
            //$.ajax({ ... });
            // 使用jQuery的.ajax()方法来发送Ajax请求。在其中设置了请求的URL、HTTP方法和数据
            $.ajax({
                url: "/add",
                method: "POST",
                data: { name: name, age: age },
                // success: function(response) { ... }
                // 这是在Ajax请求成功后的回调函数
                success: function(response) {
                    // 在这里处理Ajax响应
                    console.log(response);
                }
            });
        });
    });
</script>
</body>
</html>

执行程序

启动命令:

python app.py

访问地址:

localhost:5000

展示图

后记

觉得有用可以收藏或点赞!

相关推荐
爱写代码的小朋友9 分钟前
Python的几个高级特性
python
Eric.Lee202115 分钟前
数据集-目标检测系列- 螃蟹 检测数据集 crab >> DataBall
python·深度学习·算法·目标检测·计算机视觉·数据集·螃蟹检测
一丝晨光21 分钟前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby
Front思22 分钟前
vue使用高德地图
javascript·vue.js·ecmascript
sp_wxf43 分钟前
Lambda表达式
开发语言·python
容器( ु⁎ᴗ_ᴗ⁎)ु.。oO1 小时前
MySQL事务
数据库·mysql
蜡笔小新星1 小时前
Python Kivy库学习路线
开发语言·网络·经验分享·python·学习
篝火悟者1 小时前
问题-python-运行报错-SyntaxError: Non-UTF-8 code starting with ‘\xd5‘ in file 汉字编码问题
开发语言·python
惜.己1 小时前
javaScript基础(8个案例+代码+效果图)
开发语言·前端·javascript·vscode·css3·html5
hakesashou2 小时前
python如何比较字符串
linux·开发语言·python