How to retrieve data from database when want to retrieve data dynamically - mysql

How can I retrieve data from database(MySQL) dynamically in NodeJS when having more than one events in the database table. In the below code, I am getting data in text variable...have checked it via console but want it to get retrieved from SQL query ....so what is the correct way to get the data dynamically via query
console.log("enter to db-----------------",text)
connection.query("SELECT Description FROM tegbot_v4_xlsx WHERE Name=text", async function (error, rows, fields)
{
if (!!error)
{
console.log(`Error in the query`)
}
else
{
console.log(`Successful query\n`);
console.log('hello---------', rows[0].Description)
await dc.context.sendActivity(rows.Description)
}
})

Related

Validate existing email in mysql in a node.js server

I am having the following problem with node and mysql:
I have a function registerUser that takes the req.body with the user credentials and store them into a mysql db.
First of all I check that the email provided does not already exist. I have done this validation working with postgres in the following manner: if(user.rows.lenght!==0) return res.send("user already exist")
Then I pass to the next line of code that insrts the credentials into the db.
My problem is that using mysql, user.rows is undefined. I am having trouble extracting the data from the response which would allowme to perform some sort of validation.
My code is like this:
registerUser:async(req,res)=>{
const resolver=Resolver(res)
try {
//get data from req.body
const {userName, userEmail, userPassword}=req.body
//Check if user alreday exist on db by email
const user=db.query("SELECT * FROM users WHERE user_email=?",
[userEmail],(err,result)=>{
if(err) console.log(err)
else if(result.length!==0) return res.status(401).send('user already exist')
})
The callback function of the query does not stop the execution of the registeruser function. Also, the result comes with the user credentaials which is what I need, but I dont know how to extract it from the callback in order to use it in the scope of registerUser

Query from MySQL's database returns [Object] [Object] in node.js and JSON.stringify() do not seem to work

I am using MySQL database and have created table that stores user's characters names from my Discord Bot.
I want my bot to display this list on Discord after using command, but it just returns [object Object].
I tried JSON.stringify() but it doesn't work. Is there something more to it I don't know about?
con.query (`SELECT Name FROM ${message.author.username}list`, (err, rows) => {
if(err) throw err;
JSON.stringify(rows);
message.reply(rows);
Both with and without stringify result are as in the picture]
you should save rows data in some variable. after update you code:
con.query (`SELECT Name FROM ${message.author.username}list`,
(err, rows, fields) => {
if(err) throw err;
rows = JSON.stringify(rows);
message.reply(rows);
}

How to get one row with MySQL and NodeJS ?

I am new developer ReactJS, I develop a table with ReactJS on the FrontEnd, NodeJS on BackEnd and MySQL about the database.
I want when I click on the view button on Action column, it will be redirected to another page, which display a list containing the result of the Select query, as below :
My router :
exports.viewclient = function(req, res) {
var Code = req.query.Code;
console.log(req.query.Code);
connection.query('SELECT Code, Prenom, Nom, FAX, Telephone, Email, Adresse1, Adresse2 FROM clients WHERE Code = ?',[Code], function(error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
console.log(results);
});
}
My server :
router.get('/viewclient/:Code', clients.viewclient);
When, I test the backend with Postman, http://localhost:4000/app/viewclient/:Code=1111 , it returns : [] and console.log(req.query.Code) returns undefined
How to fix that please ?
Need a couple of changes in your URL and code
The URL should be http://localhost:4000/app/viewclient/111
In your controller
console.log(req.params);
Output
{ "Code": "111"}

can i connect to mysql database from sails without defining models?

I'm using sails.js and sails-MySQL and I want to connect to a MySQL database. I have tables, functions, and procedures in my workbench. now I want to know that is it necessary to create model files and define my schema again?
Yes, you can connect to your DB without defining models. However bare in mind that you will have to write raw queries every time. So first you need to define your DB connection in your datastores.js file. Then you can do the following in some of your controllers when you want to get something from your DB (say you have a table users and you want to get all of them):
var myDBStore = sails.getDatastore(); //gets the default datastore.
var query = "SELECT * FROM users;";
myDBStore.sendNativeQuery(query).exec(function (err, nativeResult) {
if (err) {
return res.send(err);
}
return res.send(nativeResult.rows);
});
or using the modern way in an async function:
var myDBStore = sails.getDatastore(); //gets the default datastore.
var query = "SELECT * FROM users;";
var nativeResult;
try {
nativeResult = await myDBStore.sendNativeQuery(query);
} catch (err) {
return res.send(err);
}
return res.send(nativeResult.rows);
More info here: https://sailsjs.com/documentation/reference/waterline-orm/datastores in section "Using datastores without a model"

Get data from MySQL database and pass it to jade an access it using nodejs

I have started nodejs to make a simple chat application in it.
For this I want to access all users which are in mysql database.
My code is like:
JS
exports.authenticate = function(req, res) {
//connection.connect();
var sql="SELECT * from users where username='"+req.body.user+"' and password='"+req.body.pass+"' LIMIT 1";
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
//res.send('Your data is: ', rows);
var str="Hi, <b>"+rows[0].name+"</b> ("+rows[0].email+")";
sql="SELECT DISTINCT username,name from users ORDER BY name";
connection.query(sql, function(err, datarows, fields) {
if (err) throw err;
//res.send('Your data is: ', rows+' <br/> All Users are : ', datarows.length+"<a href='/'>Login</a>");
str+='<ul style="list-style:none;width:300px">';
for(var index=0;index<datarows.length;index++)
{
str+="<li><a href='javascript:;'>"+datarows[index].name+", "+datarows[index].email+"</a></li>";
}
str+='</ul>';console.log(str);
console.log(str)//gives ul
});
str+="<a href='/'>Login</a>";
res.send(str);//this not gives the ul of other users
});
}
The above code has problems that I wrote console.log(str)//gives ul this prints the whole string like Hi, <b>Rohan</b> ("rohan#xyz.com")<ul><li><a>Something</a></li>....</ul>. But res.send(str); sends only Hi, <b>Rohan</b> ("rohan#xyz.com")<a href='/'>Login</a>.
Why this is happening?
Is my str variable not global?
Can I use res.send() many times, if yes then how?
Can I use the above code with jade then what code should I write for this.
I found this answer How to pass data form mongodb (using Mongous module) into nodejs view (using temp engine jade)? related to my problem
app.get('/', function(req, res) {
mgs(dbColl).find(function(data){
res.render('yourview.jade', { data: data });
});
});
Then,How to access data in yourview.jade
I also want to know for which type of applications we should use nodejs ?
Thank in advance.
This is happening because Node is asynchronous. Your res.send(str) is executed immediately after calling your inner connection.query(), therefore the callback which adds more hasn't executed before the send.
No, your str variable is not global.
I do not believe so. If you want to write to the response before sending it, you can use res.write().
Yes you can use Jade instead of what you're doing now. Take a look at the Jade docs. They are full of examples of variables being used in jade. To summarize it for you though, you should be able to access a variable with #{variable}.
As for your last question, I'm really not sure what you're asking. You can use node for alot of stuff, from controlling quadcopters to web sites and services.