How to make node.js and mysql work together? - mysql

Thanks in advance for your help!
I am making a node/express app and I want to use a mysql database. But I can't seem to connect to the database.
I know I'm supposed to use the node-mysql module (https://github.com/felixge/node-mysql), but I must be doing it wrong.
I'm completely new to this. Do I have to create a database and then create a table? Is there a way to create a database elsewhere so it doesn't get erased every time I restart the app?
Here's my code. Can someone answer the questions above and tell me what I'm doing wrong below? Thanks!
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
io = require('socket.io'),
path = require('path');
var app = express();
var server = http.createServer(app);
sio = io.listen(server);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var mysql = require('mysql');
var connection = mysql.createConnection({
user : 'me',
password : 'secret',
host : 'localhost',
port : app.get('port')
});
connection.connect();
connection.query('CREATE TABLE tesTable (integer int, textfield VARCHAR(100), PRIMARY KEY(integer))',
function(err, result){
if(err) {
console.log(err);
} else {
console.log("Table testTable Created");
}
});
By the way, in package.json, I listed
"mysql": "2.0.0-rc2"
as a dependency and did
'npm install'

You can just create your tables in the database as you normally do and it will be persistent enough not to be deleted anytime you restart your app. You can connect to your database by using the following code if you want:
var mysql = require('mysql');
app.use( connection(mysql, {
host: 'myhost',
user: 'user_name',
password: 'password',
port: 3306, //port mysql
database: 'database_name',
multipleStatements: 'true' //false by default
}, 'pool'));
req.getConnection(function(err, connection) {
connection.query("SELECT * FROM `table_name`;",function (error,row){
if(!error){
//do something.....
}
else console.log("Error : "+err);
});
//do something else...
});

My first suggestion, besides the question about any errors, is that you should try this
var mysql = require('mysql');
var connection = mysql.createConnection({
user : 'me',
password : 'secret',
host : 'localhost',
port : your_MySQL_port
});
The port: app.get('port') in your given example returns your http server port, but not the port of your MySQL server.
Check https://github.com/felixge/node-mysql#connection-options at 'port'.
To get your MySQL port to insert in your_MySQL_port on Linux or Mac OS, just open a terminal an type:
ps ax | grep mysqld
as result you will see something like --port=1234 in the generated output. In this case 1234 is your_MySQL_port.
In this exmaple your code should look like:
var mysql = require('mysql');
var connection = mysql.createConnection({
user : 'me',
password : 'secret',
host : 'localhost',
port : 1234
});

You might want to read a few tutorials on MySQL in general before jumping into it with Node, but in case you feel adventurous, here's a very brief tutorial on how I'd go about setting up MySQL on my machine.
I am assuming that you have access to the MySQL shell. If you're using a frontend the process may be different.
After installing MySQL and configuring an account, you'd want to log into the MySQL shell with the command
mysql -u me -p
followed by the password for the MySQL user when prompted.
Next, you'll want to create a database. You'd do this with the command
create database mydatabase;
then
use mydatabase;
Next you'll want to create a table. Run the CREATE TABLE query in the shell to set up a table. You could do this in Node, but then you'd be running the command needlessly every time you started the app.
Now you should be able to connect using node-mysql
var connection = mysql.createConnection({
user : 'me',
password : 'secret',
host : 'localhost',
database : 'mydatabase',
port : 3306 // or whatever your mysql port is
});

I was facing same issue so how i solve it...
Mysql Part
1-I have already installed wamp and can access to phpmyadmin.
2-Using phpmyadmin i have created a database and a table say it users(please insert 2,3 rows data using insert menu option) look like
check
> http://prntscr.com/72gsxc
3-Make sure wamp is running and mysql service is also running.
4-Click wamp and mouseover MYSQL and then click my.ini and search there port by default it is 3306.
Node Part
var pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'cricstream_2',
port : 3306
});
var readTable = 'SELECT * FROM countries';
pool.getConnection(function(error, connection){
connection.query(readTable, function(err, rows){
if(err) throw err;
else {
console.log(rows);
}
});
});

Do I have to create a database and then create a table?
Yes, you should create the database and the table ahead of time, that is correct.
Is there a way to create a database elsewhere so it doesn't get erased every time I restart the app?
Yes, you typically install MySQL server on a computer, this installation manages a run of databases, which you can remove/backup/duplicate etc, and create new databases. Your NodeJS app would just be making a connection to your MySQL server installation.

Related

Trying to connect the mySQL database on Railway to the backend of my React App built in Next.js but no data is showing up

I have linked my local mySQL workbench database to the deployment website "railway" - they are working and connected. If I edit one database the other updates automatically.
However in my app when I try to connect to the database now being hosted on railway my data is not displayed. If I revert to my local database it works fine.
This works okay
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "flashcards_2.0",
});
app.get("/ClassSelector/:yearId/:weekId/:classId", function (req, res) {
const yearId = req.params.yearId;
const weekId = req.params.weekId;
const classId = req.params.classId;
const q = `SELECT * FROM ${classId} WHERE year = ${yearId} AND week = ${weekId}`;
db.query(q, (err, data) => {
if (err) return res.json(err);
console.log(data);
res.json(data);
});
});
This is the data I tried with the hosted server
The railway gives me these two pieces of data in relation to the database - I have starred out the password but otherwise it is identical
mysql -hcontainers-us-west-19.railway.app -uroot -pnkEDYn2av******* --port 6177 --protocol=TCP railway
mysql://root:nkEDYn2av*******#containers-us-west-19.railway.app:6177/railway
Here is my code that I swapped in to try and the hosted server
const db = mysql.createConnection({
host: "containers-us-west-19.railway.app",
user: "root",
password: "nkEDYn2av*********",
database: "railway",
});
The axios.get() on the client side was still looking at localhost and not the http of the new hosted website. I thought that fixed it but didn't.
I still have the same problem – I still cannot seem to access the database being hosted on railway – but I am getting a new error.
This is my app
https://eb-flashcards.vercel.app/
Here is the link that should retrieve the flashcards I want...
https://ebflashcards.vercel.app/ClassSelector/2022/35/Listening%20Kiso

is it possible to connect to mysql database directly without rest api?

I'm very new to this backend stuff but I really want to know or else I can't sleep tonight or many other nightss.......
I'm tasked to build a rest API that will allow our web application to update our company's MySQL database remotely from any internet or client.
basically, the web application will be built using react framework that will allow users to take in some inputs and send them to the backend and update the MySQL database remotely.
so far, I have the rest API ready and inside this rest API i have included some mysql methods that will update the table in our database. it works fine.
but suddenly I couldn't find the reason why we need the rest API in the first place
below is the code I have...my question is
can't we just skip the express part? and directly connect the application to MySQL database using the mysql methods createConnection and then run db.query(sqlInsert) without running the app.get?
the only reason I can think of is that, if I do this, it will probably allow anyone to access the database from the browser's console. In this case, does it mean rest API is just like a filter that simply runs a server site after the user clicks the submit button, and then once the server runs it will then take the submitted information and run the db.query()? and then once that is complete, it will send back a response displayed on the server site saying its working?
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createConnection({
host:'the ip address of the computer that has the mySQL database',
user: 'the user name created in workbench',
password: 'the password created in workbench',
database: 'the database name',
port: '1234'
})
db.connect(function(err){
if(err){
console.log(err)
process.exit(1)
}
console.log("connected to mysql")
})
app.get('/', (req,res) => {
const sqlInsert = "INSERT INTO person123 (customerid, firstname, lastname) VALUES ('USv10', 'USv10', 'USv10');"
db.query(sqlInsert), (err, result) =>{
}
res.send('working')
})
app.listen(3001, () => {
console.log ('running on port 3001 yes')
})
yes you can connect with mysql without express and running restful api but
condition is that server will be running using a specific port.with only this block
of code your server is connected to databse.
var mysql = require('mysql');
var con = mysql.createConnection({
host:'the ip address of the computer that has the mySQL database',
user: 'the user name created in workbench',
password: 'the password created in workbench',
database: 'the database name',
port: '1234'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
and this block is nesecary for running server on specific port
app.listen(3001, () => {
console.log ('running on port 3001 yes')
})

How do I connect node.js to my SQL database? [duplicate]

This question already has answers here:
MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client
(32 answers)
Closed 3 years ago.
I am trying to connect node js to MySQL database which is up and running according to the MySQL Workbench. However the usual create connection code template isn't working.
Any ideas as to why this is?
I have tried putting a function and error around the connection.connect() part to see if it actually connects. But the terminal window comes up with the same error nonetheless:
Marcs-MacBook-Pro:npm-global marcwatts$ node index.js
Error while performing Query.
Do we think that it is connecting ok or does it not connect in the first place?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '<hidden from stack overflow>',
database : 'songdata'
});
connection.connect();
connection.query('SELECT * from songdata2', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection.end();
I just want to connect so I can learn how to write the code which takes each song and places its lyrics inside the Watson Tone analyzer and outputs the results in a new table in MySQL. Any advice on this part would be much appreciated too as I am new to web apps!
The recommended way to establish a connection is this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});

How to access mysql database with socket.io

I'm just getting into coding server side javascript and have been reading tutorials on socket.io and node.js, but I haven't come across anything demonstrating how to use node.js to access a mysql database.
Say for instance I want to create a method that listens to a table in my database at
mysql.something.com (with database: database, username: username, etc), how would
I get socket.io with node.js to connect to that database and listen for new input to that table and then subsequently return that input?
I'm wondering if anyone could give me a specific example that uses a publish subscribe model.
Thanks for the help.
You have to poll mysql database for changes at regular interval and when detect a change emit a socket.io event. Here's a pseudo code
var mysql = require('mysql');
var connect = mysql.createConnection({
host: 'localhost'
, database: 'your_database'
, username: 'user'
, password: 'password'});
var initial_result;
// check for changes after 1 second
setTimeout(function(){
connect.query('select * from your_table', function(err, result) {
if(err) { throw new Error('Failed');}
initial_result = initial_result || result;
if(Changed(initial_result, result)) { socket.emit('changed', result); }
});
function Changed(pre, now) {
// return true if pre != now
}
}, 1000);

Socket.io & Mysql: how many connections?

In an app with socket.io and node-mysql module, what's the best way (most optimized and well designed) to use mysql connections when an event is triggered?
create one connection and pass it to the callback
create a connection every time the callback is called
Let's write some code to better explain
Case 1
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
io.sockets.on('connection', function cb1(){
socket.on('event', function cb2(){
connection.connect(function cb3(){
connection.query();
});
});
});
Case 2
io.sockets.on('connection', function cb1(){
socket.on('event', function cb2(){
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function cb3(){
connection.query();
});
});
});
My server listen for several socket events and I'm experiencing a lot of timeout errors! I think it could be related to the use of the connections.
Any suggestions?
I think the best would be to have a connection opened all the time and run just query inside socket.io event. Like this:
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function cb3(){
io.sockets.on('connection', function cb1(){
socket.on('event', function cb2(){
connection.query();
});
});
});
I would look at connection pooling, which is implemented by node-mysql. This has the advantage of being able to use multiple connections to your database, while keeping the total number of connections limited to prevent flooding the database server.
Another possibility could be node-mysql-queues, which can be used to prevent possible issues with multiple queries run through a single connection.