我知道如何使用 Node.js 查询 SQLite 数据库以带回带有相应字段信息的特定键,但我无法找到在 Mysql 中执行此操作的正确语法。
我想在 url 中放入特定的电台名称,例如并从数据库中获取其所有信息。例子。 http://localhost:5000/station/
数据库结果将是:
[“车站”:“温顿”,“位置”:“拜尔斯巷123号”,“特性面积”:“3000”]
<sqlite> needs to be put in <mysql>
app.get('station/:stationid', req, res) => {
const stationToLookup = req.params.stationid;
db.all (
'SELECT * FROM stores WHERE station = $station',
{
$station = stationToLookup
},
(err, rows) => {
console.log(rows);
if (rows.length > 0){
res.send (rows[0]);
}else{
res.send({});
}
});
});
最佳答案
您应该首先通过 npm 安装 mysql 驱动程序。 npm install mysql
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
app.get('station/:stationid', req, res) => {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM stores WHERE station ='" + req.params.stationid + "'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
注意上面的代码中如何使用双引号和单引号。查询位于双引号内,然后我们要查找的字段值位于 =
之后嵌入双引号内的单引号之间。标志。
关于javascript - 如何使用 Node.js 查询 mysql 数据库以通过 url 中的名称(而不仅仅是 ID)获取特定用户(字段),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56712967/