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

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

Related

Connecting Nodejs with 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

mysql is not working on AWS linux instance?

I have an linux instance on AWS and MySQL database working on it. I was able to connect to the instance via workbench on my local machine. However, I am not able to connect to the database via the node js code. Below is the snippet
var mysql = require('mysql');
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"experience"
});
db.connect((err)=>{
if(err){
console.log("database error...plzz start ur xammp");
}
else{
console.log("mysql is up and running smoothy");
}
});
module.exports = db;
Can you connect to mysql using the command line in the instance using the command:
mysql -u DBUSER -h DBSERVERNAME_OR_IP -p
Or
mysql -u user_name -h mysql_server_ip_address_here -p db_name_here

Connect Express js project to external MySQL databse via SSH

I would like to know the best way to connect an Express.js project to an external MySql database using conf.ini ?
Should I use SSH ?
There is no need for ssh, mysql has it's own protocol to connect remote servers, you only need to use mysql module for nodejs, the following code is to ensure connection between hosts:
const mysql = require('mysql');
var connection = mysql.createConnection({
host : 'remote_ip',
user : 'mysql_username',
password : 'password',
database : 'database_name'
});
connection.connect( function (err) {
if (err) {
console.log('Cannot connect to mysql server', err);
} else {
console.log('Successfully connected');
}
connection.end();
});
One last thing, make sure to edit mysql config file /etc/mysql/my.cnf and set bind-address parameter to 0.0.0.0, and do not forget to restart mysql service: sudo service mysql restart

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

Acces database from appfog's node.js server (Database settings)

I'm trying to connect to a database using a node.js server both hosted on appfog.com using these settings:
var client = mysql.createConnection({
host: 'mysql-node01.eu-west-1.aws.af.cm',
user: '****#gmail.com',
password: '*******',
database: 'd2dc10d6a450048b587114fa9b11756ed',
port: 3306
});
I'm pretty sure the host, database and maybe port are incorrect but I don't know which values to use, i.e. should I use localhost?
Use the db credentials from the VCAP_SERVICES environment var and do not hard code them. The credentials are provided when the app is started on AppFog. See the Appfog Node Docs
var env = JSON.parse(process.env.VCAP_SERVICES);
var creds = env['mysql-5.1'][0]['credentials']; # grabs the creds for the first mysql database
var client = mysql.createConnection({
host: creds.hostname || 'localhost',
user: creds.username,
password: creds.password,
database: creds.name,
port: creds.port || 3306
});
I created a npm package to help facilitate getting production and development credentials. See AppFog Env
How to use it:
First set a local env var with your local dev database credentials:
export DEV_DB_CREDS='{ "username": "root", "name": "dev-db-name" }'
Then get the creds in the app:
var service = appfog.getService('mysql-db-name', process.env.DEV_DB_CREDS)
var creds = service.credentials
This method allows the same code to work locally and in production.