NodeJs insert current Datetime field into MySQL db - javascript

I'm trying to insert a DATETIME field into my MySQL db.
var dt = require('moment')().format('YYYY-MM-DD HH:mm:ss');
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id],
[dt],
(error, results, fields) => {
}
);
I get this error:
C:\Users\tiger\Desktop\prova\REST_API_WITH_MYSQL-master\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^TypeError: this._callback.apply is not a function
If I try this code, everything comes right:
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,"2021-01-27 00:00:00")`,
[results[0].id],
//[dt],
(error, results, fields) => {
}
);
What i'm doing wrong?

You have your parameters in 2 separate arrays. Put your parameters in the same parameter array.
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, dt],
(error, results, fields) => {
}
);

The correct format probably is YYYY-MM-DD HH:MM:SS(I think it depends on MySQL configuration, but this is the default) as the docs points out.
So you should try using moment's format() method like this:
const myDate = moment(data.myTime.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, myDate],
(error, results, fields) => {
}
);

Related

How to convert MYSQL Timestamp to CST time with Javascript?

If someone could help me with this I´d appreciate it!
I need to convert MYSQL Timestamp 2022-09-14T05:08:32.000Z to my local time (Central Standard Time) and then be able to pass that result to EJS. I am passing the data to my EJS view with this route, but not sure how to convert this timestamp before passing it to EJS.
This screenshot shows the 'rows' values which are being passed to EJS.
rutas.get('/historial', loggedIn, async (req, res, next) => {
await pool.query('SELECT * FROM historial WHERE id = ? AND calidaddeltrade = ? OR calidaddeltrade = ?', [req.user.id, 'Excelente', 'Buena'], function (err, rows, fields) {
if (err) { throw err };
res.render('./historial', { rows: rows});
console.log(rows);
})
});
Does anyone know how could I do this with Javascript? Thanks!!

Getting undefined variables when inserting into mariadb

I don't know what I'm doing wrong, but I get undefined variables in my query, while the variables are set. I'm trying to create a table and then put some data into it
const obj = {
time: new Date(),
taken: 0,
given: 6.4
}
const pool = mariadb.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'P1data'
})
pool.getConnection().then(async conn => {
let createLive = `create table if not exists live(
time datetime primary key,
taken float not null,
given float not null
)`
conn.query(createLive, (err) => {
if(err) console.error(err.message)
})
const res = await conn.query(`SHOW TABLES`)
console.log(res)
conn.end(err => {
if(err) console.error(err.message)
})
}).catch(err => {
if(err) console.error(err)
})
pool.getConnection().then(conn => {
conn.query(`INSERT INTO live(time, taken, given) VALUES (${obj.time}, ${obj.taken}, ${obj.given});`)
.then(rows => {
console.log(rows);
conn.end();
})
.catch(err => {
console.error(err)
})
}).catch(err => {
if(err) console.error(err)
})
The error I get looks like this:
Error: (conn=354, no: 1054, SQLState: 42S22) Unknown column 'undefined' in 'field list' sql: INSERT INTO live(time, taken, given) VALUES (undefined, 0, undefined); - parameters:[]
INSERT INTO (...) VALUES (...) expects the string values to be enclosed in quotes. And with your current method, also the datetime column probably will be converted from a string on insert, but you don't have any quotes in your query.
Furthermore your obj.time and obj.given seem to be undefined. Thus, your string template for the query evaluates exactly to
INSERT INTO live(time, taken, given) VALUES (undefined, 0, undefined);
So, what the query processor sees in the VALUES is 2 times the identifier undefined (it must be an identifier, because it's not enclosed in quotes) and in the current situation an identifier can only be a column.
You should check your object data
You should not create your queries with string templates, because even if you had the correct quotes, your app is widely open to SQL injections. Use parameterized queries as described in the documentation. Then the mariadb library will care about all necessary quotes and escaping.
conn.query("INSERT INTO live(time, taken, given) values (?, ?, ?)", [obj.time, obj.taken, obj.given])
.then( ...)

mySql Insert Syntax - Not Inserting What's Expected

I have this INSERT query. It does create a record in the table, but "client" value is 0, and "short" value is null. However, all of the console logs show the correct data. I'm assuming this is a simple syntax error in my use of the question marks. But I can't find that, or seem to get it to work using just variable names either. Any help is appreciated.
app.put("/audit/create", function (req, res) {
console.log("It is getting to the route");
const client = req.body.client;
const short = req.body.short;
console.log(`client: ${client}`);
console.log(`short: ${short}`);
connection.getConnection(function (err, connection) {
connection.query(
`INSERT INTO audits (client, short)
VALUES (?, ?)`,
[
{
client: client,
},
{
short: short,
},
],
function (error, results, fields) {
if (error) throw error;
res.json(results);
console.log(`Audit has been created`);
}
);
connection.release();
});
});
I've also tried using the variables names of ${client}, ${short} in place of the questions marks... and that still gives me the same result. However the console logs that render ${client} and ${short} do log the correct data I'm expecting to see.
Why are you passing objects as the values to the query? Try just:
connection.query(
'INSERT INTO audits (client, short) VALUES (?, ?)',
[ client, short ],
function ...

How to insert a data into a MySQL database via a variable?

I am trying to insert values defined in javascript at the start of the program. But it does not like me trying to insert variables, instead, I should enter the raw name.
This is the error code:
Error: ER_BAD_FIELD_ERROR: Unknown column 'username' in 'field list'
I am using a SQL database and javascript to interact with it. The value has been defined with a variable beforehand.
var username = "Mark Graham"
var password = 13.00
con.connect(function(err) {
var username = "Mark Graham"
var password = 13.00
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO staff (name, hours) VALUES (username, password)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
It should insert Mark Graham into the database.
Implements a ORM, Sequelize or use
connection.query('INSERT INTO staff (name, hours) VALUES (?, ?)', [YourVar,YourSecondVar], function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
or
connection.query({
sql: 'INSERT INTO staff (name, hours) VALUES (?, ?)',
timeout: 40000, // 40s
values: [varOne,varTwo]
}, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});

pass a json result of a mysql query as a param to my ejs in Node/express

I have a query to get all my users. I have been doing res.json(rows) to display to screen until now. Now I want to pass the object obtain from the query to a ejs file and display it. If I do like my code below, the object pass is a string and I can´t iterate or obtain the fields.
What is the best way to achive what I´m trying to do?
router.get("/users", (req, res) => {
const connection = getConnection();
const newLocal = "SELECT * FROM client";
connection.query(newLocal,(err, rows, fields) => {
if (err) {
console.log("Error "+err);
res.sendStatus(500);
return;
}
// res.json(rows);
res.render("users.ejs", {users: JSON.stringify(rows)});
});
});
It's because you're turning your Array rows into a String. Remove JSON.stringify

Categories

Resources