我正在尝试创建一个可以从
mysql
中的不同表中进行选择的函数
我的功能
async function getOne(table, table_parameter, parameter) {
const result = await pool.query(
`SELECT * FROM ? WHERE ? = ?`,
[table, table_parameter, parameter]
)
}
路由器:
companiesRouter.get('/:id', async (request, response) => {
const id = request.params.id
const company = await getOne('Company', 'companyID', id)
response.send(company)
})
这最终会出现错误:
sql: "SELECT * FROM 'Company' WHERE 'companyID' = '1'", sqlState: '42000', sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right
在第 1 行 ''Company' WHERE 'companyID' = '1'' 附近使用的语法” }
有什么办法可以做到这一点吗?
更新函数
getOne
中的 dbquery 格式,如下所示:
async function getOne(table, table_parameter, parameter) {
const actual_query = mysql.format(
'SELECT * FROM ? WHERE ? = ?',
[table, table_parameter, parameter]
).replace(/'/g, '');
console.log(actual_query);
await pool.query({
// sql: `SELECT * FROM ${table} WHERE ${table_parameter} = ${parameter}`,
sql: actual_query,
timeout: 30000
},
(error, results, fields) => {
if (error) throw error;
console.log('The solution is: ', results);
return results;
}
);
}
不会显示错误并正确显示结果。