I have a query:
const getRunsByProjectTable = {
text: 'Select pvt(); Execute pvtstmt;'
} ;
const getRunsByProjectTable = (req, res) => {
pool.query(queries.getRunsByProjectTable, (error, results) => {
if (error) throw error;
res.status(200).json(results.rows);
})
}
It does not return anything but on pgAdmin, I am getting the desired table. Does anyone know what the problem may be?
Related
I send my object by post request with postman then in the backend with node js recive it and update my table but it return sqlerror on string in object and no problem on integer !
1 - my obj in postman => {
"id" : 3,
"controlsCode":123456,
"controlsName" : "hamed"
}
2 - my code in node =>
async editControls(req, res) {
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName=${controlsName} where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}
}
3-error in node js =>
SQLITE_ERROR: no such column: hamed
You need single quotes around the string literal:
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName='${controlsName}' where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}
I'm relatively new to SQLite and I've been trying to modify a project made by people over at glitch. The app is supposed to save text to a database, and my project link is this. Although the logs don't show any errors. I can't get any data to save no matter what I do. (I changed the database file saving location from .data/sqlite.db to /data.sqlite.db). I assume this is some small issue I'm just new about, but I can't find anything about it on the internet.
app.use(express.static("public"));
// init sqlite db
const dbFile = "./data/sqlite.db";
const exists = fs.existsSync(dbFile);
const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database(dbFile);
// if ./.data/sqlite.db does not exist, create it, otherwise print records to console
db.serialize(() => {
if (!exists) {
db.run(
"CREATE TABLE Dreams (id INTEGER PRIMARY KEY AUTOINCREMENT, dream TEXT)"
);
console.log("New table Dreams created!");
// insert default dreams
db.serialize(() => {
db.run(
'INSERT INTO Dreams (dream) VALUES ("test"), ("hi sam"), ("fortnite gaming chair 3d")'
);
});
} else {
console.log('Database "Dreams" ready to go!');
db.each("SELECT * from Dreams", (err, row) => {
if (row) {
console.log(`record: ${row.dream}`);
}
});
}
});
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", (request, response) => {
response.sendFile(`${__dirname}/views/index.html`);
});
// endpoint to get all the dreams in the database
app.get("/getDreams", (request, response) => {
db.all("SELECT * from Dreams", (err, rows) => {
response.send(JSON.stringify(rows));
});
});
// endpoint to add a dream to the database
app.post("/addDream", (request, response) => {
console.log(`add to dreams ${request.body.dream}`);
// DISALLOW_WRITE is an ENV variable that gets reset for new projects
// so they can write to the database
if (!process.env.DISALLOW_WRITE) {
const cleansedDream = request.body.dream;
db.run(`INSERT INTO Dreams (dream) VALUES (?)`, cleansedDream, error => {
if (error) {
response.send({ message: "error!" });
} else {
response.send({ message: cleansedDream+"success" });
}
});
}
});
// endpoint to clear dreams from the database
app.get("/clearDreams", (request, response) => {
// DISALLOW_WRITE is an ENV variable that gets reset for new projects so you can write to the database
if (!process.env.DISALLOW_WRITE) {
db.each(
"SELECT * from Dreams",
(err, row) => {
console.log("row", row);
db.run(`DELETE FROM Dreams WHERE ID=?`, row.id, error => {
if (row) {
console.log(`deleted row ${row.id}`);
}
});
},
err => {
if (err) {
response.send({ message: "error!" });
} else {
response.send({ message: "success" });
}
}
);
}
});
// listen for requests :)
var listener = app.listen(process.env.PORT, () => {
console.log(`Your app is listening on port ${listener.address().port}`);
});
I'm trying to write a function that returns a query from a sqlite3 database (using Node and Express)
This is how (likely) the function is called
app.get('/example',(req,res)=>{
console.log(getThings(db_connection))
}
And this is the function per se
getThings(db){
let sql = 'SELECT * FROM Table'
let results[]
db.all(sql, (err, rows) => {
if(err){throw err}
let i
for(i=0;i<rows.length;i++){
res.push(rows[i])
}
console.log(res)
})
return res
}
I expected the rows being returned at the end, but it always returns res before populating it first, and just then it prints res with the correctly
I might have understood why it does so, but I have no idea how to fix it properly (I'm still new at JS)
Callbacks are asynchronous, so res will not be populated before the return.
You need to make your callback into a Promise or use async/await.
Promisify the callback:
getThings(db){
return new Promise((resolve, reject) => {
db.all('SELECT * FROM Table', (err, rows) => {
if (err) reject(err)
resolve(rows)
})
})
}
app.get('/example', (req, res) => {
getThings(db_connection)
.then(rows => res.send(result))
.catch(err => res.send({
error: err.message
}))
}
or
Use async/await:
Wrapped in try/catch to catch err, then because you're simply looping over the rows you don't need the for loop.
When you see the following structure object.method('param', (err, rows) => { you can almost guarantee its Promise compatible, else if not you can use util.promisify(original) to make it so.
Cleaner and more verbose then then().catch() chaining:
app.get('/example', async (req, res) => {
let result = {}
try {
result = await getThings(db_connection)
} catch (err) {
result = {
error: err.message
}
}
res.send(result)
}
async getThings(db) {
return db.all('SELECT * FROM Table')
}
I have two tables and I need data in this format. How is this Possible?
My Tables
Required Output
{
"id":"1",
"name":"akhil",
"pics": [
{
"pic1": "123.jpg",
"pic2": "123.jpg"
}
]
}
Generally I use this for getting data from single table
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const config = require('./config');
var VerifyToken = require('./VerifyToken');
const mysql = require('mysql');
app.use(express.json());
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'sample'
});
app.get('/usersdata', VerifyToken, (req, res) => {
let id = req.userId;
console.log(req.userId);
connection.query("select * from users", function (error, results, fields) {
if (error) throw error;
else {
res.send({"result": results});
}
});
})
My Solution:
app.get('/usersdata', (req, res) => {
connection.query("select u.id, u.name, p.pic1, p.pic2 from users u, pics p where u.usersid=p.id", function (error, results, fields) {
if (error) throw error;
else {
let data = results;
let newResult = {};
results.map(row => {
if(newResult[row.id]) {
newResult[row.id].pics.push(row.pic1, row.pic2)
} else {
newResult[row.id] = { id: row.id, name: row.name, pics: [row.pic1, row.pic2] };
}
})
res.send({ "result": Object.values(newResult) });
}
});
})
I would use an ORM instead of writing query myself. Check this link used for a project saved lot of time and code was cleaner.
i want to know how can i realize passing parameter to Model. I have 3 file server.js , controllers/news.js and models/news.js
Server.js
const newsController = require('./controllers/news');
server.get('/newsAll', newsController.all);
server.post('/getOneNews', (req, res) => {
db.get().query(`SELECT * FROM news WHERE id = ?`, [ req.body.id ],
(err, result, fields) => {
if (err) console.log('error SELECT one row', err);
});
});
controller/news.js
const newsModule = require('../models/news');
exports.all = (req, res) => {
newsModule.all((err, rows) => {
if (err) {
console.error(err);
return res.sendStatus(500);
}
res.send(rows);
});
};
models/news.js
const db = require('../db');
exports.all = (done) => {
db.get().query(`SELECT * FROM news ORDER BY id`, (err, rows) => {
if (err) {
console.log('error SELECT * FROM news MYSQL', err);
throw err;
}
done(err, rows);
});
};
All about method all i understood , but i want to know how can i passing [ req.body.id ] (<- from front-end) this parametr to Model for accepting ONE news from database . Whithout parameters it is very easy.
All you need is to do is grab the id from the req.params object and then set your endpoint to accept that params value.
// Server.js
server.get('/getOneNews/:id', (req, res) => {
db.get().query(`SELECT * FROM news WHERE id = ?`, [ req.params.id ],
(err, result, fields) => {
if (err) console.log('error SELECT one row', err);
});
});
Hope this helps!