JavaScript(JS)是一种广泛使用的脚本语言,主要用于网页和网络应用的前端开发。MySQL是一种流行的关系型数据库管理系统(RDBMS),用于存储和管理数据。将JavaScript与MySQL结合使用,通常需要通过后端服务器来实现数据的交互。
以下是一个简单的示例,展示如何使用Node.js和MySQL进行数据写入:
首先,需要安装Node.js和MySQL的相关依赖包:
npm install express mysql
const express = require('express');
const mysql = require('mysql');
const app = express();
app.use(express.json());
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database!');
});
app.post('/add', (req, res) => {
const { name, age } = req.body;
const sql = 'INSERT INTO users (name, age) VALUES (?, ?)';
connection.query(sql, [name, age], (err, result) => {
if (err) return res.status(500).send(err);
res.status(200).send('Data inserted successfully!');
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert Data</title>
</head>
<body>
<h1>Insert Data into MySQL</h1>
<form id="insertForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="age">Age:</label>
<input type="number" id="age" name="age">
<button type="submit">Insert</button>
</form>
<script>
document.getElementById('insertForm').addEventListener('submit', (event) => {
event.preventDefault();
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
fetch('/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, age })
})
.then(response => response.text())
.then(data => {
alert(data);
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
</body>
</html>
?
占位符)来处理用户输入。通过以上示例和解释,你应该能够理解如何使用JavaScript将数据写入MySQL数据库,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云