Reputation: 1
why this query below returns undefined in rows and field even the user table has data? how can i use the promise version properly in typescript. any help would gladly appreciate. Thank you...
code
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();
Console Output
undefined undefined
successfully connected to database
Upvotes: 0
Views: 7532
Reputation: 565
Looking at the mysql docs, I have two suggestions:
createConnection
call as well.// get the client
const mysql = require('mysql2/promise');
// get the promise implementation, we will use bluebird
const bluebird = require('bluebird');
const testConnection = async () => {
try {
// 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]);
console.log(rows, fields);
console.log('successfully connected to database');
} catch (error) {
console.log(error);
}
};
Upvotes: 3