创建与MySQL数据库的连接并连接到数据库
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345678',
database: 'virtual'
});
connection.connect();
get请求,从machine1表中查到数据
app.get('/machine1', (req, res) => {
pool.getConnection((err, connection) => {
if (err) {
res.status(500).send('Database connection error');
} else {
connection.query('SELECT * FROM machine1', (err, results) => {
if (err) {
res.status(500).send('Database query error');
} else {
res.send(results);
}
connection.release();
});
}
});
});
前端接收
function generateTable1() {
$.ajax({
url: 'http://localhost:3000/machine1',
method: 'GET',
dataType: 'json'
}).done((data) => {
// 在页面中显示表格
const table = $('<table>');
const headerRow = $('<tr>');
headerRow.append($('<th>').text('电压'));
headerRow.append($('<th>').text('状态'));
headerRow.append($('<th>').text('货量'));
table.append(headerRow);
data.forEach((user) => {
const row = $('<tr>');
row.append($('<td>').text(user.voltage));
row.append($('<td>').text(user.state));
row.append($('<td>').text(user.goods));
table.append(row);
});
$('#table-container').append(table);
}).fail(() => {
// 处理请求失败的情况
$('#table-container').text('Failed to load data');
});
}
存储图片
// 定义要插入的图片路径
const imagePath = './public/Line-20230526.jpeg';
// 读取图片文件的二进制数据
const imageData = fs.readFileSync(imagePath);
// 构造SQL语句,用于向数据库中插入图片数据
const sql = 'INSERT INTO images (name, image) VALUES (?, ?)';
const params = ['image3', imageData]; // SQL语句中的参数,包括图片名称和二进制数据
// 执行SQL查询,将图片数据插入数据库中
connection.query(sql, params, function(err, result) {
if (err) throw err; // 如果发生错误,抛出异常
console.log('Image added to database'); // 输出成功添加图片到数据库的消息
});
图片查询
app.get('/photo', (req, res) => {
const sql = 'SELECT * FROM photo';
pool.query(sql, (err, results) => {
if (err) {
console.error('Error querying database:', err);
res.status(500).send('Error querying database.');
return;
}
// 将查询结果中的 URL 地址添加到返回结果中
const data = results.map((item) => {
return {
id: item.id,
photo: item.photo // 注意这里,imgUrl 为图片 URL 地址的字段名,你需要根据实际情况进行修改
};
});
res.send(data);
});
});
前端接收图片
function generateTable3() {
$(document).ready(function() {
$.ajax({
url: 'http://localhost:3000/photo',
method: 'GET',
dataType: 'json'
}).done((data) => {
// 在页面中显示表格
const table2 = $('<table>');
const headerRow2 = $('<tr>');
headerRow2.append($('<th>').text('id'));
headerRow2.append($('<th>').text('图片'));
table2.append(headerRow2);
data.forEach((user) => {
const row2 = $('<tr>');
row2.append($('<td>').text(user.id));
const imgCell = $('<td>');
const img = $('<img>').attr('src', user.photo); // 在 img 元素中添加图片 URL 地址
console.log(user.photo)
imgCell.append(img);
row2.append(imgCell);
table2.append(row2);
});
$('#table-container2').append(table2);
}).fail(() => {
// 处理请求失败的情况
$('#table-container2').text('Failed to load data');
});
});
}