Nodejs - MySQL : How to get a specific result back to nodejs - mysql

Say I have a query like below...
SELECT
Username AS name,
Occupation AS occ,
Hobby AS hob
FROM
mt_User
At my Nodejs segment, I have...
conn.getConnection(
function (err, client) {
if(err){
console.log('Connection Error');
throw err;
}
client.query(thatQueryAbove, function(err, rows){
if(err){
console.log('Query Error');
}
var Username = rows???????
var Occupation = rows??????
var Hobby = rows???????
....How exactly do I call back the data with the alias
defined in my query like 'name', 'occ' and 'hob'?
});
});
Can anyone lemme how to retrieve the data back using the alias of my SELECT statement in Node.js?
Thank you in advance guys :)

You can use the standard Node.js driver for mysql. The code to accomplish above will look like below
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'mysqluser',
password : 'yourpass',
database : 'dbname'
});
connection.connect();
connection.query('SELECT Username AS name,Occupation AS occ,Hobby AS hob FROM mt_User', function(err, rows, fields) {
if (err) throw err;
if(rows && rows.length>0)
console.log(rows[0].name, rows[0].occ, rows[0].hob);
else
console.log('No Results Found!');
});

Related

I want my query result to be displayed in format of actual table Node.js HTML CSS

I am building a project for Database Course.
I am already done with Front End. I built the front end using Tailwind CSS.
Now I've started working on the backend and getting data from the database and display on my website using Node.js
I am a beginner and I want the result of the query to be styled and formatted like an actual table.
So I need help as I didn't find a reliable solution on the internet
I AM ATTACHING THE OUTPUT RESULT AND THE KIND OF RESULT I WANT.
Here is my Node.js code
var mysql = require('mysql');
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345678",
database: "mydb"
});
var sqlQuery = "SELECT username FROM Users";
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
// con.query(sqlQuery, function (err, result) {
// if (err) throw err;
// console.log(result);
// });
});
// display query result on host
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// display query result on host
con.query(sqlQuery, function (err, result) {
if (err) throw err;
//show result in table format
res.end(JSON.stringify(result));
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
CURRENT OUTPUT
OUTPUT I WANT

how can i insert data i got from api into mysql using nodejs?

con.connect(function(err) {
var aid = JSON.stringify(response.articles[1].author);
//if (err) throw err;
console.log("Connected!!!!!");
console.log(aid);
var sql = "INSERT INTO db1 (id,fname) VALUES (5,aid)";
if (err) throw err;
console.log("1 record inserted");
});
HERE IS MY CODE THAT IS NOT WORKING I AM USING BODY-PARSE AND EXPRESS TOO!!! but the error mentioned that in MySQL syntax how can i solve it ?
You can use Sequelize ORM for MySQL.
Sequelize Doc
Example Create Usage with ExpressJS
var username = req.body.username;
var password = req.body.password;
router.get('/create_user', (req,res) => {
user.create({
username,
password
}).then((usr) => {
res.send(usr)
})
})

Change my database result to JSON

I would like to know how to get the result of my query to be a JSON response in Node.js. Currently, I am getting a result from my DB that is in JSON but I cannot access the values in it. My code is below.
connection.connect();
connection.query('select * from ttnews order by post_date DESC Limit 0,10',
function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
responseJSON.response = results[0].headline;
callback(null, responseJSON);
By the line responseJSON.response = results[0].headline I am getting an error results is undefined
Any help will be appreciated.
Try this code
var express = require('express');
var app = express();
var mysql = require('mysql');
var readline = require('readline');
var con = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'cmd'//your database name
});
con.connect(function(err){
if(err){
console.log('Error Connecting to Database');
}
});
app.get('/', function(req, res){
con.query('SELECT * FROM ttnews order by post_date DESC Limit 0,10',function(error, data){
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});
app.listen(3000,function(){
console.log('server listening on 3000');
});
Hope this helps...
With Express 4.x, the output rows from mysql db is in json format.
For example,
sqlConnect.connection.query('SELECT * from users', function(err, rows, fields){
if (err) {
console.log("Querying error");
} else {
console.log(rows);
}
sqlConnect.connection.end();
});
The output is of the form
[ RowDataPacket {
id: 1,
username: 'Dani',
password: '1q2w3e4r',
verified: 0 } ]
So now you can get the individual values using the . operator. For example, console.log(rows[0].username) will log the value 'Dani'

How to query with node-mysql and write out the results?

I am trying to connect to a db on my hosting and write out the result, I am not getting any error, just blank space. line like console.log('test'); put at any place always work but I am not getting any query results, what am I doing wrong?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'wm51.wedos.net',
user : 'xxxxxx',
password : 'xxxxxx',
database: 'd57283_vs'
});
connection.connect();
var queryString = 'SELECT * FROM versus LIMIT 5';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log(rows[i].title);
}
});
connection.end();
(The table is called versus, has columns title, url...in adminer it's all accessible and the query works...)
Be careful with that connection.end(); call at the bottom. NodeJS is asynchronous, remember?
Try putting that at the end of the inner function after the for-loop, otherwise it will get called as soon as the query is called, possibly killing the connection you're trying to use!
perhaps mysql-server is not to be connected, when you query,or mysql-server is to be closed when you query.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'wm51.wedos.net',
user : 'xxxxxx',
password : 'xxxxxx',
database: 'd57283_vs'
});
connection.connect();
process.nextTick(function() {
var queryString = 'SELECT * FROM versus LIMIT 5';
connection.query(queryString, function(err, rows, fields) {
connection.end();
if (err) throw err;
for (var i in rows) {
console.log(rows[i].title);
}
});
});
I believe the connection.end() statement still needs to be after the for loop. Or else your ending the connection before the loop even starts.

Nodejs - Express - Mysql: render view after post

I am using express to insert/list some records from a mysql db. Everything works fine (insert/select) but how do I render the list function after insert was completed? Do I have to re-invoke the select statement?
var mysql = require('mysql');
exports.create = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('INSERT INTO wall (message) VALUES ("' + req.body.message + '")', function(err, result) {
if (err)
throw err
// is this correct? <===
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
// end
connection.end();
});
};
exports.list = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
connection.end();
};
Yes, you do have to SELECT again, and your code is generally correct. I would refactor the common part between list and the part you're asking about, I would not list users and passwords in source files, and make other minor modifications, but generally it's correct.
I read the docs more carefully and i found
res.redirect();
so for my example, it works just fine to do
res.redirect('/wall');
to make a GET request to /wall route. The data will come as this route fetching the list of messages. Thats ok for me.