HTML、JavaScript连接MySQL数据库以及对数据库的表进行修改

要使用HTML和JavaScript连接到MySQL数据库并进行表的修改,通常需要使用一个后端服务器来处理数据库的连接和操作,因为HTML和JavaScript在浏览器中运行,不适合直接连接数据库。常用的后端服务器语言包括Node.js、PHP、Python等。这里我们将使用Node.js作为后端服务器来实现这一功能。

步骤

1.安装Node.js和相关包

  • 确保你已经安装了Node.js。

  • 使用npm安装必要的包:mysqlexpress

    复制代码
    npm install express mysql

    2.设置Node.js服务器

  • 创建一个server.js文件,用于设置Express服务器并连接到MySQL数据库。

    javascript 复制代码
    const express = require('express');
    const mysql = require('mysql');
    const bodyParser = require('body-parser');
    const app = express();
    
    app.use(bodyParser.json());
    
    // 配置MySQL连接
    const db = mysql.createConnection({
        host: 'localhost',
        user: 'your_username',
        password: 'your_password',
        database: 'your_database'
    });
    
    // 连接到MySQL
    db.connect((err) => {
        if (err) {
            throw err;
        }
        console.log('MySQL connected...');
    });
    
    // 创建一个简单的API来处理数据库操作
    app.post('/modify-table', (req, res) => {
        let sql = req.body.query;
        db.query(sql, (err, result) => {
            if (err) {
                res.status(500).send(err);
            }
            res.send(result);
        });
    });
    
    // 启动服务器
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
        console.log(`Server started on port ${PORT}`);
    });

    3.设置HTML和JavaScript前端

  • 创建一个简单的HTML文件,并使用JavaScript来发送请求到Node.js服务器。

    html 复制代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Modify MySQL Table</title>
    </head>
    <body>
        <h1>Modify MySQL Table</h1>
        <form id="query-form">
            <textarea id="query" placeholder="Enter SQL query" rows="4" cols="50"></textarea><br>
            <button type="submit">Submit</button>
        </form>
        <div id="result"></div>
    
        <script>
            document.getElementById('query-form').addEventListener('submit', function (e) {
                e.preventDefault();
                const query = document.getElementById('query').value;
                fetch('/modify-table', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ query })
                })
                .then(response => response.json())
                .then(data => {
                    document.getElementById('result').textContent = JSON.stringify(data, null, 2);
                })
                .catch(error => {
                    document.getElementById('result').textContent = 'Error: ' + error;
                });
            });
        </script>
    </body>
    </html>

    运行步骤

  • 确保MySQL服务器正在运行,并且你有一个可用的数据库。

  • your_usernameyour_passwordyour_database替换为实际的MySQL凭据。

  • 启动Node.js服务器:

html 复制代码
node server.js
  • 打开浏览器并访问http://localhost:3000

  • 在文本框中输入SQL查询并提交,例如CREATE TABLE test (id INT, name VARCHAR(50))

这样,你就可以使用HTML和JavaScript通过Node.js服务器连接到MySQL数据库并进行表的修改。请注意,直接在前端输入和执行SQL查询存在安全风险,建议在实际应用中进行适当的安全验证和权限控制。 但是这样的步骤会遇到一个问题:已拦截跨源请求:同源策略禁止读取位于 file:///modify-table 的远程资源。(原因:CORS 请求不是 http)下一篇我将把解决方法发出来遇到相同问题的可以参考参考

我的个人博客

相关推荐
Larcher3 小时前
React Router 不只是页面跳转:从 SPA 路由到权限守卫的完整实践
javascript·后端
Larcher3 小时前
大模型为什么每次回答都不一样?一文搞懂 Temperature、Top K 与 Top P
javascript·后端
名字还没想好☜5 小时前
Python f-string 进阶:数字格式化、对齐填充、调试 = 号与嵌套表达式
开发语言·数据库·python·字符串格式化·f-string
ltl6 小时前
Serverless 数据库弹性理论:Neon 与 Aurora Serverless v2
数据库
Dxy12393102167 小时前
Python 如何使用 MySQL 的事务
python·mysql
eric-sjq7 小时前
10 分钟实战:用 0.6B 本地模型生成中文网页(WanlyFrontend + 编译器全流程)
javascript·机器学习·自然语言处理·html
To_OC7 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
kyriewen8 小时前
面试官问"这段逻辑为什么这样写"——我才发现,这半年我写的代码,我自己都解释不了
前端·javascript·面试
一壶浊酒..8 小时前
Scrape Webpack练习
开发语言·javascript·webpack
marvelyu10 小时前
每天10分钟学会OceanBase系列(Day 20):跨机房容灾实战——构建多数据中心高可用架构
java·大数据·数据库