I am trying to connect NodeJS with MySQL database.I am using WAMP. It's connected only default database like "mysql"and"information_schema" but those databases i created not connect with NodeJs and given me following error.
Please let me know where i am going wrong.
Code
**Server.js**
----------
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
app.use(bodyParser.json());
var connection = mysql.createConnection({
host : "localhost",
user : "root", //User Name
password : "", // No password
database : "techbiz", // Database Name
multipleStatements:true
});
connection.connect((err)=>{
if(!err)
{
console.log("Database connected ");
}
else{
console.log(err) }
})
// Initialize port
const PORT = process.env.PORT || 5000;
// send rquest to web page
app.get('/',(req,res) => res.send(`Automize Business Solution running on :${PORT}`));
app.listen(PORT,()=>console.log("Server is running"));
[Database][1]
**Error**
----------
Server is running
{ Error: ER_BAD_DB_ERROR: Unknown database 'techbiz'
at Handshake.Sequence._packetToError (K:\WebProjects\MySQL\abs-server\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (K:\WebProjects\MySQL\abs-server\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (K:\WebProjects\MySQL\abs-
at Socket.<anonymous> (K:\WebProjects\MySQL\abs-
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
code: 'ER_BAD_DB_ERROR',
errno: 1049,
sqlMessage: 'Unknown database \'techbiz\'',
sqlState: '42000',
fatal: true }
[1]: https://i.stack.imgur.com/E9MSc.png
Thanks
i just change my wamp version and using MySQL 5.5.8 , and now same code working fine.
thanks
Related
I want to connect my web application which is in development phase to the MySQL database image deployed on a VM in the oracle cloud infrastructure. Currently, I have been able to deploy the MySQL database image on the VM instance and I am able to connect to it through the CLI as well as from Workbench installed on my remote pc and create and query databases from the CLI. The database changes (new db, table creation, updation) are represented in the Workbench as well as any other remote environment that I use to connect to the VM.
So I believe the database has been correctly deployed.
The problem that I am facing right now when I try to connect to the MySQL DB from within any of my applications is that I get some connection timeout error and I am not able to connect to it from within my code. I am new to this and I am not able to understand the reason behind this. I have spent quite a few days to figure out the problem. Any help would be greatly appreciated.
I am using Sequelize ORM and mysql2
Below is my config.json file for connecting with the remotely deployed database:
{
"development": {
"username": "root",
"host": "193.122.62.76",
"dialect": "mysql",
"password": "*****",
"database": "test"
}
Server.js file for setting up the server
const express=require('express')
const app=express()
app.use(express.json())
app.use(express.urlencoded({extended:true}))
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header('Access-Control-Allow-Methods', "POST, GET, PUT, DELETE, OPTIONS");
next();
});
var models=require('./models')
models.sequelize.sync().then(function(){
console.log('Database looks fine')
}).catch(function(err){
console.log(err,'Something went wrong with the db')
})
require('./routers/index')(app)
port=process.env.PORT || 3000
app.listen(port,console.log('server up'))
index.js file in models:
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
The connection timeout error that I get:
ConnectionError [SequelizeConnectionError]: connect ETIMEDOUT
at ConnectionManager.connect (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:126:17)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async ConnectionManager._connect (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:318:24)
at async D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:250:32
at async ConnectionManager.getConnection (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:280:7)
at async D:\Notes\Node\servertest\node_modules\sequelize\lib\sequelize.js:613:26
at async MySQLQueryInterface.createTable (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\query-interface.js:225:12)
at async Function.sync (D:\Notes\Node\servertest\node_modules\sequelize\lib\model.js:1300:5)
at async Sequelize.sync (D:\Notes\Node\servertest\node_modules\sequelize\lib\sequelize.js:793:35) {
parent: Error: connect ETIMEDOUT
at Connection._handleTimeoutError (D:\Notes\Node\servertest\node_modules\mysql2\lib\connection.js:178:17)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
},
original: Error: connect ETIMEDOUT
at Connection._handleTimeoutError (D:\Notes\Node\servertest\node_modules\mysql2\lib\connection.js:178:17)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
} Something went wrong with the db
The timeout error is typically caused by not being able to establish a connection to the server. Make sure that your mysql server is running where you are trying to connect to, as well as making sure the host ip/port entered are correct. Also important to verify that the firewall is configured to allow access.
Connecting will also require proper policy in place to allow user access which I am guessing you do have but can't hurt to verify. You can review connecting to a DB system using OCI here - https://docs.cloud.oracle.com/en-us/iaas/Content/Database/Tasks/connectingDB.htm
Node js with mysql rest api GETTING Error: getaddrinfo ENOENT localhost::
In mysql phpmyadmin i have creates database named job_portal with same username and password.
webapp.js :
const express = require("express");
const app = express();
const cors = express("cors");
const dotenv = require("dotenv");
dotenv.config();
const dbService = require("./config/database");
const { response } = require("express");
//app.use(cors());
app.use(express.json());
//app.use(express.urlencoded({ extended : false }));
app.listen(process.env.app_port, () => {
//console.log("server running....", process.env);
console.log("server running on port....", process.env.app_port);
});
database.js :
const mysql = require("mysql");
const dotenv = require("dotenv");
dotenv.config();
//const { response } = require("express");
//let instance = null;
const connection = mysql.createConnection({
host : process.env.host,
user : process.env.user,
password : process.env.password,
database : process.env.database
});
console.log("process.env.db_port", process.env.user)
connection.connect((err) => {
if(err){
console.log(err);
}
console.log('db:: '+connection.state);
});
.env :
node_env = development
app_port = 5000
db_port = 3306
host = localhost
user = job_portal
password = job_portal
database = job_portal
connectionLimit = 10
Now facing error log:
process.env.db_port job_portal
server running on port.... 5000
Error: getaddrinfo ENOENT localhost
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
--------------------
at Protocol._enqueue (C:\xampp\htdocs\projects\job portal in jquery\webservices\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\xampp\htdocs\projects\job portal in jquery\webservices\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\xampp\htdocs\projects\job portal in jquery\webservices\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (C:\xampp\htdocs\projects\job portal in jquery\webservices\config\database.js:14:12)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18) {
errno: 'ENOENT',
code: 'ENOENT',
syscall: 'getaddrinfo',
hostname: 'localhost',
fatal: true
}
db:: disconnected
how should i fix this issue please help me to resolve
Good mornig to you guys. I want to establish a connection to a remote mysql database using node js. but i am facing this error. I do not know if I wrongly specifies the access path to the db
code
var mysql = require('mysql');
var pool = mysql.createPool({
host: "http://kamerun-it.com/mysql",
connectionLimit : 100,
database: "****",
user: "****",
password: "*****",
multipleStatements: true
});
error
throw err;
^
Error: getaddrinfo ENOTFOUND http://kamerun-it.com/mysql
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
--------------------
at Protocol._enqueue (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (F:\kamerun it\aspi-api\node_modules\mysql\lib\Connection.js:119:18)
at Pool.getConnection (F:\kamerun it\aspi-api\node_modules\mysql\lib\Pool.js:48:16)
at Object. (F:\kamerun it\aspi-api\app\model\db.js:16:8)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http://kamerun-it.com/mysql',
fatal: true
}
You probably have an error in your config with the host URL.
Here's a working example with a connection to a remote MySQL:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "remotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
and here's one with mistaken host parameter:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "WRONGremotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
The second one returns the same ENOTFOUND error.
Check if that's the correct URL, if the database can be accessed remotely and via which port you can use it.
I have created a mysql database on google cloud that I'd like to access from a separate node web application (also running on google cloud). I am testing the connection locally on my computer first, and when I run the following code locally I can successfully establish a connection to my database and see the data in it.
'use strict';
// [START app]
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const mysql = require('mysql');
var connection = mysql.createConnection({
host : 'Cloud SQL IP',
user : 'username',
password : 'password',
database : 'db_name'
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// Make globals.js accessible
app.use(express.static(__dirname + '/'));
app.get('/', (req, res) => {
connection.connect();
connection.query('SELECT * FROM Users', function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
res.status(200).send('Hello World!');
});
app.get('/login', (req, res) => {
res.status(200).send();
});
// [START server]
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
// [END app]
However when run this same code in my google app engine (for both debugging on port 8080 and fully deployed on https://myapp.appspot.com) I get the following timeout error:
{ Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:419:13)
at Socket.g (events.js:292:16)
at emitNone (events.js:86:13)
at Socket.emit (events.js:185:7)
at Socket._onTimeout (net.js:338:8)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
--------------------
at Protocol._enqueue (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:130:18)
at app.get (/home/megan_cooper2900/journeyma/app.js:31:13)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at next (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at /home/megan_cooper2900/project/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/megan_cooper2900/project/node_modules/express/lib/router/index.js:335:12)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }
Why is this not working on the Google App Engine application?
In your connection configuration for mysql,host does not work on App Engine. You have to use socketPath . socketPath is the path to a unix domain socket to connect to. When used host and port are ignored. (transferred knowledge from using Loopback on App Engine flex. it had me banging my head for days lol). It's value is your Cloud SQL Instance connection name
so in your case, it should look like this: /cloudsql/my-project-12345:us-central1:mydatabase
var connection = mysql.createConnection({
socketPath : '/cloudsql/my-project-12345:us-central1:mydatabase',
user : 'username',
password : 'password',
database : 'db_name'
});
It's a similar process if you're using Postgres on GCloud which is answered here
I also did faced the same issue and I was using Kubernetes pods to access my CloudSQL instance. I got a fix by increasing the timeout in the configuration.
cloudSqlConfig: {
connectionLimit: 10,
host: 'your-host-ip',
user: process.env.DB_USERNAME,
password: process.env.DB_PASSKEY,
database: 'myDB',
connectTimeout: 20000,
waitForConnections: true,
queueLimit: 0
},
I get this error when I try to connect to mysql database on phpmyadmin from nodejs . I am using same port number 3306 that is for mysql.After 4,5 seconds i get this error. I am using mamp free version for this .
connect ETIMEDOUT at Connection._handleConnectTimeout
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//constants
const STATUS_SUCCESS = "success";
const STATUS_FAILURE = "failure";
mysql
var connection = mysql.createConnection({
host : '172.0.0.1',
user : '****',
password : '****',
database : 'parking_application'
});
connection.connect();
app.listen(4567,'localhost',function(){
console.log("server started");
});
Please Help.
Thanks in advance.
var mysql = require('mysql');
var connection = mysql.createConnection({
socketPath : '/Applications/MAMP/tmp/mysql/mysql.sock', //path to mysql sock in MAMP
user : 'userdb',
password : 'password',
host : '127.0.0.1',
database : 'yourdatabase'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
Add the socket MAMP path to mysql (mysql.sock) in the json object connection.
Restart your server.
172.0.0.1. it's actually 127.0.0.1 or just use localhost