I am trying to connect mysql with node.js but I got an undefined when I do console.log(result). This is my code:
dbConnection.js
const mysql = require('mysql');
module.exports = () => {
return mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'news_portal'
});
}
news.js
const dbConnection = require('../../config/dbConnection');
module.exports = app => {
const connection = dbConnection();
app.get('/', (req, res) => {
connection.query('SELECT * FROM news', (err, result) => {
console.log(result);
});
});
}
The database has info, and the user and password is correct. Can someone help me? Thanks.
I finally solve it. err var contained Client does not support authentication protocol requested by server; consider upgrading MySQL client. And I found a solution to that error in this post
Basically what I did was:
use mysql;
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'YOUR_MYSQL_PASSWORD'
Thanks for the help.
Related
Trying to run the server for making app get then insert into mysql table those register's, but it's not working. Someone have anything that can help me with that? I try to find something about in mysql doc, but nothing that can solve. It seems like i create a connection on MySQL Workbench, but this connection is somehow addressed wrongly on Workbench or on my index.js
MySQL Workbench
index.js file
const express = require("express");
const app = express();
const mysql = require("mysql");
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "a",
database: "crudgames",
})
app.get('/',(req,res) => {
let SQL = "INSERT INTO games ( name, cost, category) VALUES ( 'Far cry 5', '120', 'Aventura' )";
db.query(SQL, (err, result) => {
console.log(err);
})
})
app.listen(3001, () =>{
console.log("rodando servidor");
});
Does anyone know why my request just gets stuck loading when trying to access my database ?
My database name is test. If set the database: books or something like that for example. Then it returns the error database is unknown: books so I assume that my password is correct it just isn't finding the test data base ?
// To import these packages remember to add "type":"module" to package Json
import express from "express";
import mysql from "mysql";
const app = express();
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "keks000207",
database: "test",
});
// This is an API request with an Express server
app.get("/", (req, res) => {
res.json("Hello this is the backend");
});
app.get("/books", (req, res) => {
const q = "SELECT * FROM books";
db.query(q, (err, data) => {
if (err) return res.json(err);
return data;
});
});
app.listen(8800, () => {
console.log("Connected to backend!");
});
Try db.connect() or similar method available in the file itself.
And Instead of return data inside the callback of db.query, you should use res.send(data), then you will get the response in the GET /books API.
I. I made the code below but I recently learned about pool connection, which according to what I read are better. I just don't understand how to export the connection to a different file. So, if you could guide me on how to do it I would appreciate it. Thanks.
connection.js:
var mysql = require('mysql');
const con = mysql.createConnection({
host:'127.0.0.1', // host of server
user:'root', // MySQL user
password:'BLABLABLA', // MySQL password
database: "rpg"
});
exports.con = con
database.js:
const con = require('./connection').con;
mp.events.add('playerJoin', (player) => {
con.query('INSERT INTO BLA BLA BLA', function (err, result) {
//ETC ETC
Basically, I want to know how to export, import and make a query. I'm using MySQL Workbench 8.0. Thank you very much.
The code for creating a pool is very similar to the code you have right now. The only difference is there's the extra step of requesting a connection from the pool.
connection.js
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 10,
host: "localhost",
user: "user",
password: "password",
database: "rpg"
});
exports.pool = pool;
database.js
const pool = require("./connection").pool;
// Ask the pool for a connection
pool.getConnection((err, conn) => {
if(err){
// Do something with the error
} else {
// Do something with the connection and release it after you're done
conn.query('INSERT INTO BLA BLA BLA', (err, rows) => {
// Do something with the result
// release the connection after you're done so it can be reused
conn.release();
});
}
});
I'm using the mysql module in Node.js. In my model file, currently, I'm specifying the connection constants in each method. However, this is taking up a lot of space and I know it's not ideal.
Here's what that looks like.
doSomething: () => {
var connection = mysql.createConnection({
host : config.database.host,
database : config.database.database,
user : config.database.user,
password : config.database.password
});
connection.query( ... );
connection.destroy();
},
doSomethingElse: () => {
var connection = mysql.createConnection({
host : config.database.host,
database : config.database.database,
user : config.database.user,
password : config.database.password
});
connection.query( ... );
connection.destroy();
},
Could anyone recommend a way to tidy things up a bit and reduce the redundant code here?
Create the connection once and pass it to module exports.
const mysql = require("mysql");
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "db"
});
module.exports = conn;
Then you can import it in other files and use it.
var dbConnection = require('./dbConnection');
dbConnection.query();
However, instead of using createConnection, I recommend using createPool instead.
Connections can be pooled to ease sharing a single connection, or
managing multiple connections.
const mysql = require("mysql");
const conn = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "db"
});
module.exports = conn;
You can use it like this. Make sure to release the connection after fetching data from the table:
var connectionPool = require('./dbConnection');
connectionPool.getConnection((err, connection) => {
connection.query('SELECT * FROM table', (error, result) {
connection.release();
if(error) throw error;
});
});
To close all connections in the pool:
connectionPool.end(function (err) {
// all connections in the pool have ended
});
I have 3 files. db.js, app.js, commentController.js.
I am including my connection in every request in my app so that I wont be repeating the code connection again and again. Is this a bad / unsecure practice? Is there a better/proper way to implement this?
db.js
const mysql = require('mysql');
const pool = mysql.createPool({
host : 'host',
user : 'user',
password : 'password',
database : 'dbname'
});
exports.pool = pool;
app.js
const db = require('./db');
app.use((req, res, next) => {
req.pool = db.pool;
next();
});
commentController.js
exports.showComments = (req, res) => {
req.pool.getConnection((err, conn) => {
conn.query(`SELECT * FROM comments`, (err, results, fields) => {
conn.release();
if (err) throw err;
res.render('comments', { results });
});
});
};
If your only reason for doing this is to avoid duplicating code, then I think it's a bad idea. People looking at your code (or you looking at your code in a year) aren't going to naturally expect a db connection to be a property of req. And you aren't saving yourself any trouble really.
Just require() the database pool in the file and use it.
commentController.js
const db = require('./db');
require() will return the same pool to all your modules.
It's also not clear why you are requesting a connection rather than using the pool (I'm making some assumptions about the lib you're using).
Normally you should be able to do:
const db = require('./db');
exports.showComments = (req, res) => {
db.query(`SELECT * FROM comments`, (error, results, fields) => {
if (err) throw err;
res.render('comments', { results });
});
});
This saves the trouble of requesting and returning connections and just lets the pool do it's work.