I have a project in NoseJS and Typescript in which I am creating a generic mysql method using the promise-mysql module.
This is my mysql-connect.ts file:
import { databaseKeys } from '../models/mysql.models'
import getProperty from '../properties/properties.json'
const mysql = require('promise-mysql');
import * as logger from 'winston';
const keys_database: databaseKeys = {
socket: getProperty.mysql.port,
host: getProperty.mysql.host,
user: getProperty.mysql.user,
pass: getProperty.mysql.password,
db: getProperty.mysql.database
}
const pool = mysql.createPool(keys_database);
pool.getConnection()
.then((connection: any) => {
pool.releaseConnection(connection);
logger.info(`DB is Connected - ${keys_database.db}`);
}).catch(function (err: any) {
logger.error('Database Error: ' + err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
logger.error('Database connection was closed');
}
if (err.code === 'ER_CON_COUNT_ERROR') {
logger.error('Database has too many connections');
}
if (err.code === 'ECONNREFUSED') {
logger.error('Database connection was refused');
}
});
export default pool;
This is the method from where I call mysql to perform a query:
import * as logger from 'winston';
import * as getProperty from '../json/product.json';
import pool from '../../generic/utils/mysql-config'
import { ListProductBatchModel, ResultMsg } from '../models/listProduct.models';
export class ListProductBatchUtils {
public async getDataProduct(codProduct: string): Promise<ListProductBatchModel> {
try {
let selectTest: string = `
select * from test_bbdd.cli
`;
let query = await pool.query(selectTest);
logger.info('getDataProduct()')
return Promise.resolve(query);
} catch (error) {
logger.info(JSON.stringify(error));
return Promise.reject(error);
}
}
}
Upgrade:
I have tried to change the version of the promise-mysql package to 3.3.1 and now it connects.
The problem is that now it shows an access error but the credentials are fine because I have tried the connection in another separate code and it works:
This is the new error:
[winston] Attempt to write logs with no transports {"message":"Database Error: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: NO)","level":"error"}
This is the old connection I have:
const mysql = require('promise-mysql');
export class connectBBDD {
public async base() {
const pool = mysql.createPool({
host: 'localhost',
port: '3030',
user: 'root',
password: 'root',
database: 'test_bbdd'
});
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query('select * from cli', function (error, results) {
console.log(results);
if (error) throw error;
});
});
}
}
This is what it returns:
[ RowDataPacket { id: 7, name: 'test1', phone: null },
RowDataPacket { id: 8, name: 'test2', phone: 111 }]