How write a code which will bring me items from MYSQL-DB which will match some of the letters with request? For example I write to the end of link "samsung" but the name of item is "samsung s9, s8 etc...". How to get all of items? This is my code which is note work.
app.get('/models/:name', (req, res, next)=>{
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE name=?'
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> Error! Sorry for error, we are working on it!');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})
You have to use wildcard character % like 'SELECT * FROM products WHERE name=%anyMobileName%'
IMO Instead of creating MYSQL query from your own and executing these use Sequelize ORM
Related
I'm using a tutorial to do JWT/bcryptjs auth and then INSERT into a SQlite
table.
Thing is the tutorial is for MySQL and I get errors like db.query is not a function
and db.escape is not a function
The db :
const sqlite3 = require('sqlite3').verbose()
const DBSOURCE = "./src/db/db.sqlite"
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
}else{
console.log('Connected to the SQLite database.')
}
});
module.exports = db
Example query :
db.query(
`SELECT * FROM users WHERE LOWER(username) = LOWER(${db.escape(
req.body.username
)});`,
(err, result) => {
if (result.length) {
return res.status(409).send({
msg: 'This username is already in use!'
});
} else { .........
My best guess is that the functions are different?
How do I get this right?
There are a lot of proprietary functions in MySQL that will not work with standard SQL in other database systems.
That is just the beginning of the differences between Mysql and SQLite
Provide some query examples and we may be able to assist you with each one.
-- update after your addition of query code...
Here is an example of sqlite-nodejs
const sqlite3 = require('sqlite3').verbose();
// open the database
let db = new sqlite3.Database('./db/chinook.db');
let sql = `SELECT * FROM users WHERE LOWER(username) = LOWER(?)`;
db.all(sql, [req.body.username], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row.name);
});
});
// close the database connection
db.close();
I'm trying to make a command that get the selected queries from a table where the id is the one i use in the command, for example: !db 1 but I'm having a problem.
The problem is that the result is empty.
My code:
const Discord = require('discord.js');
const mysql = require('mysql');
module.exports.run = async (bot, message, args, connection) => {
const asd = args.slice(1,2).join(' ');
let querystring = `SELECT * FROM test WHERE id = '${asd}'`
connection.query(querystring, function (err, results, rows) {
if (err) throw err;
console.log(results);
});
}
module.exports.help = {
name: "db"
}
I appreciate any help! Thanks!
From the screenshot you posted earlier, your id column is a type INT. This code is searching as if the column is a VARCHAR.
Try this:
const id = args.slice(1, 2).join(' ');
if (isNaN(id)) { return; } // if the input isn't a number
connection.query(`SELECT * FROM test WHERE id = ${Number.parseInt(id)}`, (err, res, rows) => {
if (err) throw new Error(err);
console.log(res);
});
Important: This code allows SQL Injection. Template literals do not protect against this.
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!');
});
Evening stack! Tonight I decided to play around with some NodeJS and I'm having a little trouble understanding the appropriate way for me to handle errors in this situation.
I have a table that simply stores playerName and the name must be unique. So rather than just try to insert and get an error, I want to first make a select and if I get a result, return a 400 to the user and let them know the name already exists. If not, continue on as normal, insert the name, and return a 203.
What I've got clearly isn't working. I've attempted a try/catch and that didn't work. And I clearly can't return an error with the methods I'm using. So what's a good way to go about this?
router.post('/addPlayer' , function(req, res, next){
var playerName = req.body.name;
if(playerName === undefined || playerName.length === 0)
{
return res.status(400).send('No name provided');
}
var query = 'SELECT name FROM players WHERE name LIKE ?';
var inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err, results){
if(err) return res.status(500).send('Error connecting to database.');
if(results.length !== 0) return res.status(400).send('This name has already been used.');
});
query = 'INSERT INTO players (name) VALUES(?)';
inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err){
if(err) return res.status(500).send('Error connecting to database.');
});
res.status(201).send("Added player: " + playerName);
});
In this current version my obvious problem is Node crashes complaining about not being able to set the headers after they've already been sent. I know what I need to do. Which is end the execution of the route and return the error to the browser, but I'm just not clear on how to best go about that.
I'm using the Express framework and mysql.
Thanks.
The problem is you're running both queries in parallel. So the INSERT is executed before the response of the SELECT is received. Which means that there is a race condition. Both queries tries to send res.status() but one will happen after the other which causes the error.
To fix this, wait until the SELECT is received then do your INSERT:
var query = 'SELECT name FROM players WHERE name LIKE ?';
var inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err, results){
if(err) return res.status(500).send('Error connecting to database.');
if(results.length !== 0) return res.status(400).send('This name has already been used.');
query = 'INSERT INTO players (name) VALUES(?)';
inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err){
if(err) return res.status(500).send('Error connecting to database.');
res.status(201).send("Added player: " + playerName);
});
});
Is there anything wrong with sending the error(err) itself? For example:
if (err)
res.send(err);
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.