[英]How to use mysql in node with Typescript
I'm making a simple website with node and typescript.我正在用节点和打字稿制作一个简单的网站。 I installed MySQL module to communicate with a database.我安装了MySQL 模块来与数据库进行通信。
I'm trying to get data from DB, but I don't know how to determine what type the result should have.我正在尝试从 DB 获取数据,但我不知道如何确定结果应该具有什么类型。 For example,例如,
const sql = `SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'`;
const result = await this.pool.query(sql);
console.log(result);
in this case, the result is [ RowDataPacket { metaValue: 'map-79.jpg' } ]
.在这种情况下,结果是[ RowDataPacket { metaValue: 'map-79.jpg' } ]
。 How can I get map-79.jpg
from the result?如何从结果中获取map-79.jpg
? What type the result should be?结果应该是什么类型?
it will return Object Array :它将返回对象数组:
const sql = `SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'`;
const result = await this.pool.query(sql);
console.log(result);
result.forEach(row => {
console.log(row.metaValue)
})
Or you Can create array by using map
或者您可以使用map
创建数组
let imgArray = result.map(row => { return row.metaValue });
console.log(imgArray);
@Pushpendra Kumar was right. @Pushpendra Kumar是对的。 But we need type guard before using result as Array like below.但是在使用 result 作为数组之前,我们需要类型保护,如下所示。
const sql = `SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'`;
let rows = await this.pool.query(sql);
if ( Array.isArray(rows) ) {
return rows[0].metaValue
}
I use let records: youDefinedInterface[] = [].slice.call(result, 0);
我使用let records: youDefinedInterface[] = [].slice.call(result, 0);
to cast the Query type to a normal array.将 Query 类型转换为普通数组。
@Pushpendra Kumar @Byeongin Yoon watch out for such sql notation, @Pushpendra Kumar @Byeongin Yoon提防此类sql符号,
SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'
should be SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'
应该是
SELECT metaValue FROM ? WHERE metaKey = ?
and then pass params as arrays. 然后将参数作为数组传递。
Sanitise your queries guys. 对您的查询进行消毒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.