使用nodejs保存DateTime mysql

时间:2013-08-02 17:10:06

标签: javascript mysql node.js

我希望在Datetime字段中保存Date 对于插入我没问题... 我尝试了很多尝试,这是最后一次,但结果是相同的

插入:

var now = new Date();
var jsonDate = now.toJSON();
var then = new Date(jsonDate);


var o_voto_foto = {
    profilo_id: profilo,
    foto_id: data.id_foto_votata,
    punteggio: data.voto,
    proprietario_id: data.proprietario_foto,
    created: then
};


connection.query('INSERT INTO prof_voto_foto SET ?', o_voto_foto, function(error, rows) {
    if (error) {
        var err = "Error on INSERT 'votoFotoFancybox': " + error;
        console.error(err);
        throw err;
    }

更新表:

var now = new Date();
var jsonDate = now.toJSON();
var then = new Date(jsonDate);

connection.query('UPDATE prof_voto_foto SET punteggio = ' + data.voto + ', created = ' + then +' WHERE profilo_id = ' + profilo + ' AND foto_id = ' + data.id_foto_votata, function(error, rows) {
    if (error) {
        var err = "Error on UPDATE 'votoFotoFancybox': " + error;
        console.error(err);
        throw err;
    }

我发现了这个错误:

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Aug 02 2013 19:03:13 GMT+0200 (CEST) WHERE profilo_id = 103 AND foto_id = 5' at line 1

4 个答案:

答案 0 :(得分:12)

在@tadman的帮助下,它有效

created = new Date();
connection.query('UPDATE prof_voto_foto SET punteggio = ' + connection.escape(data.voto) + ', created = ' + connection.escape(created) + ' WHERE profilo_id = ' + connection.escape(profilo) + ' AND foto_id = ' + connection.escape(data.id_foto_votata), function(error, rows) {

答案 1 :(得分:9)

由于您正在使用当前时间戳,因此您可以考虑使用NOW() MySQL函数,而不是从javascript填充日期。当然,这意味着您将标准化MySQL服务器时间的所有时间戳,而不是客户端的时间,这可能是也可能不是。

用法如下:

UPDATE prof_voto_foto SET punteggio = ' + data.voto + ', created = NOW() WHERE profilo_id = ' + profilo + ' AND foto_id = ' + data.id_foto_votata

答案 2 :(得分:4)

日期需要包含在"'中,以便mysql知道它正在处理字符串并可以将其转换为日期时间。

UPDATE prof_voto_foto SET punteggio = ' + data.voto + ', created = "' + then +'" WHERE profilo_id = ' + profilo + ' AND foto_id = ' + data.id_foto_votata

可能需要格式化以匹配mysql所期望的内容,Aug 02 2013 19:03:13 GMT+0200 (CEST)需要转换为'YYYY-MM-DD HH:MM:SS'

答案 3 :(得分:0)

var o_voto_foto = {
    profilo_id: profilo,
    foto_id: data.id_foto_votata,
    punteggio: data.voto,
    proprietario_id: data.proprietario_foto,
    // just delete the stuff you add here :) then add created = now() on the sql statement. that should do the trick
};


connection.query('INSERT INTO prof_voto_foto SET **created = now(),** ?', o_voto_foto, function(error, rows) {
    if (error) {
        var err = "Error on INSERT 'votoFotoFancybox': " + error;
        console.error(err);
        throw err;
    }

在更新时执行相同的操作,