How to connect with mysql in config file? - mysql

What im trying to do is to connect MySQL database in my project in the config file.
config/db.js
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
})
const connectDb = async () => {
const conn = await connection.connect(function (err) {
if (err) {
return console.error("error: ", err.message);
}
console.log("Connected to MySql server");
});
};
server.js
const connectDB = require("./config/db");
connectDB();
I have done this by fare and in my terminal is shown this error: TypeError: connectDb is not a function
How can I connect MySQL in the config file?

you'll need to export the connection verb, and delete the whole "connectDb" function
config/db.js
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
})
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
server.js
const database = require("./config/db");
database.queryOrAnythignElse();
You'll probably want to learn again the basics of js and what is module.exports and etc...

Related

I'm trying to connect to the DB, but the connect() function doesn't seem to work

const express = require('express')
const app = express()
// const mysql = require('mysql')
const mysql = require('./db')()
const cors = require('cors')
require('dotenv').config();
const port = process.env.PORT || 5000
app.use(express.json())
app.use(cors())
app.listen(port, () => console.log(`${port}`))
app.get('/', (req, res) => {
res.send("hi")
})
const connection = mysql.init()
mysql.open(connection)
This is my server.js code.
const mysql = require('mysql')
require('dotenv').config();
module.exports = function() {
return {
init: function () {
return mysql.createConnection({
host: process.env.HOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE,
port: process.env.PORT
})
},
open: function(con) {
con.connect(function(err) {
// if (err) throw err
// console.log('Connected!')
if(err) {
console.log('mysql connection error: '+err)
} else {
console.log('mysql is connected successfully.')
}
})
}
}
}
And this is my db.js code...
I expect the port number and message "mysql is connected successfully" to be printed when this code is executed. But when I run it, nothing is output except for the port number. Even an error message.
So I can't verify that the database connection was made properly. Why is the contents of the connect() function not executed?
You have used same environment variable for server port and database port. Please change variable name PORT of database port to DB_PORT in .env file. Then change the environment variable name in the database port of db.js file as well.
db.js
const mysql = require("mysql");
require("dotenv").config();
module.exports = function () {
return {
init: function () {
return mysql.createConnection({
host: process.env.HOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE,
port: process.env.DB_PORT,
});
},
open: function (con) {
con.connect(function (err) {
// if (err) throw err
// console.log('Connected!')
if (err) {
console.log("mysql connection error: " + err);
} else {
console.log("mysql is connected successfully.");
}
});
},
};
};
example .env file
PORT=8080
HOST=localhost
USER=root
PASSWORD=root
DATABASE=dbname
DB_PORT=3306

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

How can I see all the databases of connected server in nodejs postgres/mysql

**I connected to the Postgres server using Nodejs and now I want to see all the databases under the connected server. Please help me **
Please see below for mysql database:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("show databases", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
SQL
SELECT datname FROM pg_database
WHERE datistemplate = false;
Example
const { Pool, Client } = require('pg')
const pool = new Pool({
user: 'dbuser',
host: 'database.server.com',
database: 'mydb',
password: 'password',
port: 5432,
})
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
pool.end()
})
const client = new Client({
user: 'dbuser',
host: 'database.server.com',
database: 'mydb',
password: 'secretpassword',
port: 3211,
})
client.connect()
client.query('SELECT datname FROM pg_database WHERE datistemplate = false;', (err, res) => { console.log(err, res) client.end() }
)

How can I connect to mysql from nodejs?

I am working on a node JS project with mysql database. I have created a new file db.js that is used to connect to the database. My structure looks like below.
- server
- config
- db.js
- index.js
db.js
const mysql = require('mysql');
export default() =>{
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: 'socha'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
}
index.js
const express = require('express');
const dbConfig = require('./config/db');
const app = express();
My problem is I cannot connect to the db.js file from index.js file.
Can anybody tell me what mistake I have been doing.
Thank You
You can change your index.js and db.js to this.
This should create the connection if DB credentials are correct
db.js
const mysql = require('mysql');
const connect = () => {
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: 'socha'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
}
module.exports = {
connect
}
index.js
const express = require('express');
const dbConfig = require('./config/db');
const app = express();
// Connecting to db
dbConfig.connect();

Connection to Database and Create a database in Node

I've tried to implement this code and terminal throws error something like this stucked in it As I've applied this code but it throws the error
"Access denied for user ''#'localhost' to database 'mydb'"
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "myusername",
password: "mypassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
create a config folder and create a file databaseConfig.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection =mysql.createConnection(config); //added the line
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
module.exports ={
connection : mysql.createConnection(config)
}
create a app.js file
var express = require('express');
var cors = require('cors');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
create a controller.js file
var config = require('../../databaseConfig.js');
var connection= config.connection
connection.query ('CREATE DATABASE mydb', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});