Javascript possibly disturbing Mysql query

Asked

Viewed 77 times

1

I recently started working with SQL databases and have had problems storing date columns in my tables. Basically what happens when I try to store a variable in the format yyyy-mm-dd, for example 2016-12-23, something gives age and what enters the table is 0000-00-00. I tried to change the type of the date variable to text and the stored value was 1981, subtraction 2016 - 12 - 23 = 1981. Has anyone ever had this problem or know how to solve it? I am writing my project in Node using the Mysql NPM module.

var temp = "1994-03-09";
newStaticQuery = {
    sql: `INSERT INTO SaudeParamEstaticos (idPaciente, data, steps) VALUES (${id}, ${temp}, ${activity[property][0].value})`,
    timeout: 10000
}
connection.query(newStaticQuery, function(err, rows, fields) {
    console.log(err);
    console.log(rows);
});

Here is a simple example of my problem, following the code below, the date is entered correctly in the table but when trying to put it in a temporary variable as in the above case the problem happens.

newStaticQuery = {
    sql: `INSERT INTO SaudeParamEstaticos (idPaciente, data, steps) VALUES (${id}, '1994-03-09', ${activity[property][0].value})`,
    timeout: 10000
}
connection.query(newStaticQuery, function(err, rows, fields) {
    console.log(err);
    console.log(rows);
});

It would be a question of javascript syntax?

  • 1

    I just read the Handbook on how to NOT ask stackoverflow questions and I wanted to thank you for the constructive comments to my question which is my first on this site as well as the patience with all the "atrocities" I committed in my beginner’s innocence. Thank you stackoverflow community for the absence of negativity.

1 answer

3


It would be the case to add the quotes in the template of query also:

sql: `INSERT INTO ... VALUES (VALUES (${id}, '${temp}', ${activity[property][0].value})`
                                             ^-aspas-^

Since it is only a substitution of values, if passing without the quotation marks is generated something like this...

VALUES (1, 1994-03-09, 489)

...instead of generating like this:

VALUES (1, '1994-03-09', 489)

and really, without the quotation marks, Mysql will handle the information numerically, calculating the value, as you had already noticed with the tests.

  • It worked perfectly! Thank you @Bacco, a merry Christmas!

  • Equally for you, family and friends. (and the whole site staff ;) )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.