1.用mysql创建用户表,然后在一个js文件中,完成数据库的增删改查。用户表的字段如下: id,int,自动编号 uname,varchar(20) upwd,varchar(40), birthday,date
时间: 2024-05-07 12:18:39 浏览: 101
首先,你需要在 MySQL 中创建一个名为 users 的表,定义其字段如下:
```
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
uname VARCHAR(20) NOT NULL,
upwd VARCHAR(40) NOT NULL,
birthday DATE NOT NULL
);
```
然后,在一个 JavaScript 文件中使用 mysql 模块,连接数据库并进行增删改查操作。以下是一个简单的例子:
```javascript
const mysql = require('mysql');
// 创建连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test'
});
// 连接数据库
connection.connect((err) => {
if (err) throw err;
console.log('Connected to database!');
});
// 新增用户
const addUser = (uname, upwd, birthday) => {
const sql = `INSERT INTO users (uname, upwd, birthday) VALUES (?, ?, ?)`;
const values = [uname, upwd, birthday];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log(`Added user with ID ${result.insertId}`);
});
};
// 删除用户
const deleteUser = (id) => {
const sql = `DELETE FROM users WHERE id = ?`;
const values = [id];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log(`Deleted ${result.affectedRows} user(s)`);
});
};
// 更新用户信息
const updateUser = (id, uname, upwd, birthday) => {
const sql = `UPDATE users SET uname = ?, upwd = ?, birthday = ? WHERE id = ?`;
const values = [uname, upwd, birthday, id];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log(`Updated ${result.affectedRows} user(s)`);
});
};
// 查询所有用户
const getAllUsers = () => {
const sql = `SELECT * FROM users`;
connection.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
});
};
// 查询指定用户
const getUserById = (id) => {
const sql = `SELECT * FROM users WHERE id = ?`;
const values = [id];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log(result);
});
};
// 添加用户
addUser('tom', '123456', '1990-01-01');
// 删除用户
deleteUser(1);
// 更新用户信息
updateUser(2, 'jerry', '654321', '1995-05-05');
// 查询所有用户
getAllUsers();
// 查询指定用户
getUserById(2);
```
这是一个简单的例子,你可以根据实际需求进行修改和扩展。注意,在实际生产环境中,为了安全起见,应该对输入的数据进行合法性校验和防注入处理。
阅读全文