Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am getting RowPacketData after executing a query, now I want to convert that RowPacketData to an array so that I can perform different operations on it.
var query = `Select products.*, product_images.Image_Name
from products INNER JOIN product_images
ON products.Id=product_images.Product_Id ORDER BY Id limit ${LimitNum} OFFSET ${startNum}`;
db.query(query , function(err,rows, fields)
{
if (err)
{
res.status(500).send({ error: 'Following Error Occured : '+ err });
console.log('Following Error Occured : ' + err);
}
else
{
res.json(rows);
console.log('20 Products Displayed on Page : ' + page);
}
})
Note : I am using node js.
I think your problem is with your db connection. You should add a check for the db connection before you do the query.
See here for example:
https://www.w3schools.com/nodejs/nodejs_mysql_select.asp
Your query and code looks correct. Start with a simpler query and expand it slowly(This will detect error in query) and also make the connection at same place with error handling. To 100% sure you have a connection.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("Select * from products limit", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
PS: I can not make comment so needed to write an attempt on answer directly. However should be good to know if you are sure you have a connection, so that can be taken out of the problem equation.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am following this tutorial here, crud app with node js and mysql.
My database, crud_app has a table named crud_table, and crud_table has got 3 columns, id, names, and date_added.
I am trying to make a SQL query using node js
async getAllData() {
try {
const response = await new Promise((resolve, reject) => {
const query = "SELECT * FROM names"
connection.query(query, (err, results) => {
if (err) { reject(new Error(err.message))}
resolve(results)
})
});
console.log(response);
return response;
} catch (error) {
console.log(error)
}
}
But I get this error
Error: ER_NO_SUCH_TABLE: Table 'crud_app.names' doesn't exist
And again I went to PHPMyAdmin to run this query in the console.
SELECT * FROM names
Output
It is claiming that the names column does not exist but you can clearly see the column here
Is there any way I can resolve this problem?
Your table name is crud_table and within your table you have the column names. You cant select all the date from a column by using SELECT * on the column,with SELECT you select data from your table in your case crud_table,so if you want all the names then try this "SELECT names FROM crud_table"
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);
});
con.connect(function(err){
if(err) throw err;
console.log("Connected!");
var sql = "USE test; INSERT INTO emails (FirstName, Email) VALUES ('Gaz', 'gmail');";
con.query(sql, function(err, result){
if(err) throw err;
console.log("Row inserted at position");
})
});
I'm trying to use node.js to insert a new row in an already existing table in MySQL. I connect properly but then an error is thrown in the console log which says the SQL syntax is wrong but I have checked and the sytax set for the sql variable works fine in SQL. The .query(sql, function()) format seems to be correct according to w3schools and other sources. I can't tell what the problem is.
According to this answer you should enable multiple statements option when creating connection to be able to use multiple statements. check the answer for more information.
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
multipleStatements: true
});
I am running a query which gives me confusing results. I have a node.js server which takes some user input from a form on the client side and uses socket.io to get the input on the server. here is the function which runs after receiving user input
databaseCheck(data);
function databaseCheck(userInput){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '12.34.56.78',
user : 'user',
password : 'password',
database : 'db'
});
connection.connect();
var query = connection.query('SELECT * from `table` WHERE `email` = userInput', function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log("connection failure");
});
connection.end();
}
So when ever I use this code, it keeps printing "connection failure" to the screen. It doesn't happen when I replace userInput with the "example#email.com" so I'm guessing there is some problem with using the variable userInput in the query. Can someone tell me what is wrong with my code?
Not only do you need to pass the userInput by appending it to the string, you need to escape it so that the query recognizes it as a string:
connection.connect();
var query = 'SELECT * from `table` WHERE `email` = ' + JSON.stringify(userInput);
console.log(query);
connection.query(query, function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log(err.name, err.message);
});
connection.end();
It also helps to make the error message more informative by displaying the actual error instead of a generic message.
Lastly, put connection.end(); inside the callback. According to what you said, it appears to work like you had it but it's generally a bad idea to end a connection before an asynchronous process using the connection has called back.
Ignore my last comment, it appears I was wrong in this particular case. According to the repository documentation, it says:
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
Try this for testing and resolution. Printing to the log will let you see what you are putting in the query.
var querystring = "SELECT * from table WHERE email LIKE " +
userInput;
console.log(querystring);
var query = connection.query(querystring, function(err, rows, fields) {...
I am trying to validate user using below code:
function validateUser(adminEmailId, adminPassword) {
try{
console.log('email id: '+adminEmailId+' password: '+ adminPassword);
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'somePassword',
database: 'someDatabase'
});
var query = connection.query('select id from AdminData where adminEmail = "'+adminEmailId+'" AND adminPassword = "'+adminPassword+'"');
console.log('query: ' + query);
query.on('error', function(error){
console.log('A db error occurred: '+error);
});
query.on('result', function(result){
console.log('some result: '+ result);
if(result.id === null) {
console.log('user not found');
}
else
{
console.log('user found :)');
}
});
}
catch (ex) {
console.log('some exception ' + ex);
}
}
The last two logs which it is printing in console are -
email id: d#g.com password: gfdgdf
query: [object Object]
It should have printed -
user not found
// OR
user found :)
I tried verifying if SQL is running properly or not by firing this in command line:
mysql -h127.0.0.1 -uroot -p
It showed me error:
Command not found
So I updated the path by using below command:
export PATH="/usr/local/mysql/bin:$PATH"
Then I was able to use mysql from command line, but still there is no success achieved in Node.js code :(
Any suggestions?
If your query results in no error or result events, then that means the query resulted in an empty set. You should listen for the end event so that you know when the query is done executing. Then you can set some condition inside the result event handler that you check on end to see if the user was found or not.
Probably an easier way to do this is to just pass a callback to query() since it doesn't seem like you will need to be streaming rows in this case. Something like:
connection.query('select id from AdminData where adminEmail = "'+adminEmailId+'" AND adminPassword = "'+adminPassword+'"', function(err, rows) {
if (err) {
console.log('A db error occurred: ' + err);
return;
}
if (rows && rows.length)
console.log('user found :)');
else
console.log('user not found');
});
Also I should point out a couple of other things:
You should not concatenate user-submitted data into SQL query strings as it leaves you susceptible to SQL injection attacks. You should at least escape the values, but it's recommended to use real prepared statements. The mysql module currently does not support real prepared statements, but mysql2 does. mysql2 is API-compatible with mysql and is substantially faster overall.
You should probably have a callback parameter at the end of your validateUser() parameter list so that you can call a callback when the query is finished, allowing you to appropriately continue execution of your code. Otherwise the place where validateUser() is called will have no idea when the query finishes and what the result was.