results undefined in querying Mysql Nodejs - mysql

I trying to get result query from mysql database in Nodejs, but the 'results.affectedRows' is always 'undefined'. I'm currently using Mac. I hope you interest for answer my question. Following this my code:
const expres = require('express');
const mysql = require('mysql');
const app = expres();
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "sistemizin"
});
console.log("Connected!");
app.set('view engine', 'hbs'); app.use(expres.static('publik'));
app.get('/', (req, res) => {
res.render('cobaview');
});
app.post('/', (req, res) => {
var contoh = `SELECT namamatkul FROM matkul_dosen WHERE idmatkuldosen = 70`;
connection.query(contoh, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
console.log('Results counted:' + results.affectedRows);
});
connection.end();
res.end();
});
app.listen(8084);
console.log("server is running at http://127.0.0.1:8084/");

results.affectedRows is returned only in case of insert, update or delete query. Since yours is a select query, result is as expected.

Related

Node + Express application returns 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR'?

I'm trying to build an application with Node and Express, it worked well yesterday until today I got this error:
{
code: "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR",
fatal: false
}
Google says I should use createPool rather than createConnection, but I'm not sure how to do it in my case. Here is my code:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const SELECT_ALL_USERS_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema'
});
connection.connect(err => {
if (err) {
return err
}
});
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /mySchema to see contents')
});
app.get('/myTable', (req, res) => {
connection.query(SELECT_ALL_USERS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
}
})
});
app.listen(4000, () => {
console.log('MySchema SQL server listening on PORT 4000');
});
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema'
});
// for an example.....
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
app.get('/myTable', (req, res) => {
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});
});
If you would like to close the connection and remove it from the pool, use connection.destroy() instead. The pool will create a new connection the next time one is needed.
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
When a previous connection is retrieved from the pool, a ping packet is sent to the server to check if the connection is still good.
you can follow this link: https://github.com/mysqljs/mysql#pooling-connections
To help other people, thought I'd post the complete solution which worked for me:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /mySchema to see contents')
});
const SELECT_ALL_USERS_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/myTable', (req, res) => {
connection.query(SELECT_ALL_USERS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
console.log(connection);
});
});
app.listen(4000, () => {
console.log('MySchema SQL server listening on PORT 4000');
});

NodejS express ReferenceError: connection is not defined

I am creating a simple server application using the following code
const express = require('express');
const mysql = require('mysql');
const PORT = process.env.PORT || 3000;
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'mydata',
});
connection.connect(function (err) {
err ? console.log(err) : console.log(connection);
});
require('./routes/html-routes')(app);
app.listen(PORT, () => {
console.log('app running on port %s', PORT);
});
module.exports = app;
in file server.js
and then a route in file html-routes.js
const mysql = require('mysql');
module.exports = function (app) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
to get data from database
I get the error
ReferenceError: connection is not defined
at /Users/arjunbhandari/Desktop/GL-IT/backend/routes/html-routes.js:5:5
I have struggled for the past 6 hours and cannot understand the problem.
Thanks
As the error states, there is no connection defined (or inherited) within ./routes/html-routes.js.
You still can pass the connection property as a second argument to your exported function:
const mysql = require('mysql');
module.exports = function (app, connection) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
then update the route mounting call within your main server file:
require('./routes/html-routes')(app, connection);
You should review your route implementation logic as this should not be the best design approach to use data-store connections.

Node.JS, Get function & Connection to XAMPP DB doesn't work

I'm using the XAMPP software as a local DB and trying to get into the get function at the below with no success.
In addition, I can not see any console comments as well:
Web error
Node.js
Thank you for your help!!
var express = require('express');
const cors = require('cors');
var app = express();
var corsOptions=
{
origin: 'http://localhost:3000',
optionsSuccessStatus: 200,
allowHeaders: ['sessionId', 'Content-Type'],
exposedHeaders: ['sessionId'],
credentials: true,
}
app.use(cors(corsOptions));
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "apptxtproject"
});
app.get("/getnetworks"), (req,res)=>{
con.query(`SELECT * FROM appadtxt`, function (err, result, fields) {
if (err) throw err;
console.log(result)
})
}
app.listen(4000, function () {
console.log('Haydeeeeee!!!');
})
In your app.get you have a bad syntax error try this:
app.get("/getnetworks", (req, res) => {
con.query(`SELECT * FROM appadtxt`, function(err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Routing to other url in node.js

I am currently working on a project where I have CRUD operation using node.js and mysql.
var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var con = mysql.createConnection({
host: "database",
user: "admin",
password: "pass",
database: "db"
});
var app = express();
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM shops where id =33", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.use('/shop', function(err) {
con.query("SELECT * FROM shops where id =34", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.listen('3000', () => {
console.log('Server started on port 3000');
});
I want to get the shops data using localhost:3000/shops and brands data using localhost:3000/brands. But i don't know how to do that because i am very new in node.js. Infact,Today i my first day. I someone gives me som demo project or some thing like this. I will be very thankful.
app.get('/brands',(req,res) =>{
//inside query
})
like...thiss

How to create a webservice using node.js to insert data into mysql?

I've a table in mysql that i need to be populated by calling a webservice.
The catch is, I would like to pass the data to be inserted into the database as parameters to the webservice.
How would I do this?
Using the MySQL module
http://npmjs.com/mysql
const mysql = require('mysql');
const express = require('express');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret',
database: 'my_db'
});
connection.connect();
app.get('/', (req, res) => {
connection.query(`SELECT * FROM table`, (error, data) => {
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});
app.post('/update/user/:id?', (req, res) => {
const id = req.params.id;
const username = req.body.username;
connection.query(`UPDATE MyGuests SET username='${username}' WHERE id=${id}`, (error, data) => {
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});