Connecting Nodejs with Mysql - mysql

I was trying to connect nodejs with mysql(first time).i am following w3schools.
Before running the below code i have installed ('npm install mysql').And the website mentioned ou can download a free MySQL database and Once you have MySQL up and running on your computer, you can access it by using Node.js.
i have installed mysql ,but how to start and run it in windows,please help.
var con =mysql.createConnection({
host:"localhost",
user:"root",
password:" "
});
con.connect(function(err) {
if(err) {
console.log("Error")
}
else
console.log("Connected!");
});

Install mysql2 npm i mysql2
const mysql = require("mysql2")
const pool = mysql.createPool({
host: "localhost",
user: "root",
database: "databasename"
password: "when you install mysql workbench at a time you set"
});
module.exports = pool.promise();
If not set password on workbench make it empty
Import In your app.js or server.js if this file outside app.js or server.js file

Related

Can't add new command when connection is in closed state (express.js + mysql2 + mysql2/promise + clearDB + heruko)

i am facing thi error whenever i make a second call to the api i created using mysql2+expressjs+clearDB(on HERUKO)+heruko deployment server
this is my code ....
const [rows,fields]= await db.execute(MYQUERY,[myarguments])
i am calling the mysql server like this with asyn/await functionality which mysql2 provides
import mysql from 'mysql2/promise'
after that i create the the connection
let db = await mysql.createconnection({
host: 'localhost',
user: "root",
password: "asdzxcasdzxc123123",
database: "doctorapp"
})
export { db }
Any sollution to this error...???
i was facing this error in mysql2/promise
Reason for this error
The actual problem is with mysql2/promise .
when you create your connection with mysql database with mysql2 npm package
this thing is causing the error...
Sollution to this error
i solved this error by creating my connection with mysql.creatPool(yourCredentials)
creat your db config file like this
import mysql from 'mysql2'
let db = mysql.createPool({
host: 'Enter your host here',
user: "enter user name here",
password: "enter you password",
database: "enter the database name",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
export { db }
Use of db in your contollers or router should be like this
const promise = db.promise()
const select_user_query=`
select *
from users
`
const [rows,fields]= await promise.execute(select_user_query)
return res.status(200).json({users:rows})
One thing to note===>
you have to create
const promise= db.promise()
in all the contollers ... so it will automatically handles all the required connnection release or other things required to make the connection working perfectly

How do I create a mysql database for my nodejs project?

This should be really basic and simple to do but I can seriously not find any understandable information on how to create a simple database for my nodejs typescript project.
I have installed the following packages with npm:
mysql2
sequelize
sequelize-cli
sequelize-typescript
I have attempted the following commands at the terminal
C:\repos\NodeNew>mysql2 -u root -p
'mysql2' is not recognized as an internal or external command,
operable program or batch file.
C:\repos\NodeNew>mysql -u root -p
'mysql' is not recognized as an internal or external command,
operable program or batch file.
C:\repos\NodeNew>node mysql2 -u root -p
module.js:538
throw err;
^
Error: Cannot find module 'C:\repos\NodeNew\mysql2'
at Function.Module._resolveFilename (module.js:536:15)
at Function.Module._load (module.js:466:25)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
C:\repos\NodeNew>
So how do I CREATE my database so I can connect to it with sequelize etc?
The tools you have installed are only for connecting a Node.js app to MySQL and do not include command-line tools to manage the MySQL server.
I will assume you have installed MySQL and it's running – you should then be able to find its mysql.exe command line client in the bin/ directory in the server's installation directory. If you haven't fiddled with authentication, just running it might work.
When you get to a MySQL prompt, you can follow any old instructions for creating a database; CREATE DATABASE foo; is the gist of it (authentication and permissions being a different story).
Since you're on Windows, you might want to look into HeidiSQL – it's been a while since I've used it, but it's a decent graphical MySQL management tool.
You can also use mysql2 to create the database – illustrated below – but I recommend getting a management tool.
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'mysql',
});
connection.query('CREATE DATABASE foo');
You should have MySQL installed on your computer, to install mysql on Windows see the following page: MySql
Once you have MySQL up and running on your computer. Open the Command Terminal and execute the following:
npm install mysql
Now you have downloaded and installed a mysql database driver. Node.js can use this module to manipulate the MySQL database:
var mysql = require('mysql');
To create a conecction create a file connection.js:
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
to test it save the file and run:
node connection.js
Which will give you this result:
Connected!
It can be solved using beforeConnect hook of sequelize as below:
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const { host, port, username, password } = config;
# create sequelize instance without providing db name in config
sequelize = new Sequelize('', username, password, config);
sequelize.beforeConnect(async (config) => {
const connection = await mysql.createConnection({ host: host, port: port, user: username, password: password });
await connection.query(`CREATE DATABASE IF NOT EXISTS \`${process.env.DB_NAME}\`;`);
config.database = process.env.DB_NAME;
});
Config.json file contains configurations for different dbs like
{
"development": {
"username": "root",
"password": "init#123",
"host": "mysqldb",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"host": "127.0.0.1",
"dialect": "mysql",
}
}
Database name is provided after db connection and creation(if required) in sequelize beforeConnect hook

mariadb for node.js ER_ACCESS_DENIED_ERROR Access denied for user

I am using the following code to establish connection to a MariaDB 10 server:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "local_ip",
user: "username",
password: "my_password",
port: 3307,
database: "name_of_db",
});
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
The SQL-Server is running on a machine within a local network.
The SQL-User is granted connections from all hosts (%).
I am able to establish a connection with a SQL GUI tool, with exact the same user.
Seems to me like a bug inside the mysql node package, anybody encountered such a problem?

node.js-mysql connection failed on windows7

I am just getting started with nodejs.
My question is that i get an Error:
connect ECONNREFUSED
npm install mysql;
server.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
port: '3306'
});
connection.connect(function(err) {
if(err) {
console.log(err);
}
});
connection.end();
Finally
1.I don't know the "user" and "password";
2."In mysql.conf, comment skip-networking.", I can't find mysql.conf;
3.I have tried this and it's not working, my platform is windows 7.
var client = mysql.createClient({
user: uuuu,
password: pppp,
host: '127.0.0.1',
port: '3306',
_socket: '/var/run/mysqld/mysqld.sock',});
It's clear you have not install mysql server in your windows yet. So you should go to http://www.mysql.com and download the server, install and set up, you can set your username and password and grant privilege to it, so you will know the user and password, and mysql.conf will be inside your installation. And if you are in windows, generally you would not use a UNIX socket to build the connection. So "_socket: '/var/run/mysqld/mysqld.sock'" should not be here.

Can't connect to localhost database from node.js server

Been having a lot of trouble trying to connect to to my localhost database. I've tried using the mysql and mysql-simple node modules but in both cases I just can't get it to connect.
Here's what I used with the 'mysql' module:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : '8000',
user : 'uber',
password : 'pass',
});
connection.connect(function(err) {
if (err) throw err;
console.log('Connection Successful');
});
connection.query('USE someDB', function(err) {
if (err) throw err;
console.log('Query Successful');
});
And here' what I used with the 'mysql-simple' module:
var database = require('mysql-simple');
database.init('uber', 'pass', 'mysql', 'localhost', 8000);
database.querySingle('SELECT Host FROM user', function(err, results) {
if (err) {
console.log('error fetching some active users: ' + err);
return;
}
log('Query Successful');
for (var i = 0; i < results.length; i++)
console.log('got active user ' + results[i]);
}
In both cases, when I run my node.js server, it never logs that its connected. I've tried replacing localhost with '127.0.01' and creating a new user to make sure the password is correct, but to no avail. Why isn't it connecting?
Thanks
It's most likely that networking is turned off, that means that mysql server communicates with clients via UNIX sockets and not via TCP/IP. You can check that out running mysql client and run "status" command. If you see port number there, then your mysql server communicates via TCP/IP, or else you'll see something like "socket pathname…", get the pathname and give it to node.js connection parameters, e.g.
...
socketPath: '/opt/lampp/var/...',
...
Check that out in https://github.com/felixge/node-mysql page (search for "socketPathname")
Hope, that's your problem.
You should use mysql_config to show the path to socket.
This a sample on my MAC
QuyLes-MacBook-Pro:freelancer quyle$ mysql_config
Usage: /Applications/MAMP/Library/bin/mysql_config [OPTIONS]
Options:
--cflags [-I/Applications/MAMP/Library/include -fno-omit-frame-pointer -g -DNDEBUG]
--include [-I/Applications/MAMP/Library/include]
--libs [-L/Applications/MAMP/Library/lib -lmysqlclient -lz]
--libs_r [-L/Applications/MAMP/Library/lib -lmysqlclient_r -lz]
--plugindir [/Applications/MAMP/Library/lib/plugin]
--socket [/Applications/MAMP/tmp/mysql/mysql.sock]
--port [0]
--version [5.5.42]
--libmysqld-libs [-L/Applications/MAMP/Library/lib -lmysqld]
--variable=VAR VAR is one of:
pkgincludedir [/Applications/MAMP/Library/include]
pkglibdir [/Applications/MAMP/Library/lib]
plugindir [/Applications/MAMP/Library/lib/plugin]
and then, you add key socketPath for yourMysqlConnection.
bellow on my sample
MysqlServer: {
adapter: 'sails-mysql',
host: 'localhost',
user: 'root', //optional
password: 'root', //optional
database: 'nodejs', //optional,
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
},
change this
database.init('uber', 'pass', 'mysql', 'localhost', 8000);
to
database.init('uber', 'pass', 'mysql', 'localhost', 3306);
and you should be through
Make sure that MySQL and express are running on the same port.
I had MySQL bundled from XAMPP, that ran on Port 3036.
On setting app.listen to 3036, my code worked. FINALLY!
Try this code it's work for me
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : '',
database : 'urdatabase',
}
);
connection.connect();
query = connection.query("SELECT * FROM UrTable;");
query
.on('error', function(err) {
console.log( err );
})
.on('result', function( data ) {
socket.emit('YourData',data);
});
I hope this will be helpful for you
In my case, anything happened, so I solved by generating new GRANTs with a new user for nodejs apps
Its due to the networking is turned off in MySQL configurations.
In Ubuntu 20.04.2 and MySQL 8.x.x(its worked in my case) you can find this settings in
/etc/systemd/system/mysql.service.d/override.conf
there will be a ExecStart key and its have multiple configurations.
Here you can provide --skip-networking as OFF
--skip-networking=OFF
And you have to restart your service
systemctl restart mysql.service
It will allow you to connect localhost