为什么下面的查询在行和字段中返回undefined,即使用户表有数据?如何在typescript中正确使用promise版本。任何帮助都将不胜感激。非常感谢。
代码
import mysql from 'mysql2';
import 'dotenv/config';
import bluebird from 'bluebird';
//? this all configuration for database connection
const connection: any = mysql.createConnection({
host: process.env.DB_HOSTNAME,
user: process.env.DB_USER,
database: process.env.DATABASE,
Promise: bluebird,
});
//! test connection - required
const testConnection = async () => {
try {
//? output to the console the query value
let [rows, fields]: [any, any] = await connection.execute(
'SELECT * FROM user',
);
console.log(rows, fields);
console.log('successfully connected to database');
} catch (error) {
console.log(error);
}
};
testConnection();
控制台输出undefined undefined
successfully connected to database
查看mysql文档,我有两个建议:
- 我发现您需要更改正在导入的内容
- 此外,您还需要等待
createConnection
呼叫
// get the client
const mysql = require('mysql2/promise');
// get the promise implementation, we will use bluebird
const bluebird = require('bluebird');
// create the connection, specify bluebird as Promise
const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test', Promise: bluebird});
// query database
const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);