当列类型为DATE时,MYSQL在SELECT查询上返回完整的datetime字符串

cra*_*208 3 mysql datetime date node.js

在Google进行了许多研究之后,我很难找到问题的答案,但是我的说法似乎不够准确,无法为我的问题提供正确的答案。

我有一个数据库,用于存储有关客户的信息:名字,姓氏,生日等。

该问题特定于我的生日栏。该类型设置为DATE,对于每个结果,一切都在phpmyadmin中显示为DATE,但是当我在脚本中使用SELECT检索行时,将返回生日日期列,就像它是DATETIME类型一样,除非该值为0000- 00-00。

我正在使用node-mysql从我的应用程序中的mysql表检索结果。我在node-mysql之上构建了一个模块,以缩短池化所需的代码,这正是DatabasePool函数的来源。这是一个示例node.js代码,从中显示了行为:

property: {
    get: function(id, callback) {
        mysql.DatabasePool(function() {
            this.query('SELECT birthdate FROM ICM_Contact WHERE ICM_contact_id = ? LIMIT 1', [id], function(err, rows, fields) {
                console.log(rows[0]);
                callback(null, ICM.contact.revive(rows[0]));
            })
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

对于给定的日期:2015-08-11,它将返回{ birthdate: Tue Aug 11 2015 00:00:00 GMT-0400 (EDT) },但是对于日期注册,它将{ birthdate: '0000-00-00' }按预期返回。

我不知道为什么phpmyadmin无论如何都能正确显示日期,但是当我从脚本执行查询时,它不会正确返回日期。

我尝试了以下操作:datetime mySQL SELECT only date

property: {
    get: function(id, callback) {
        mysql.DatabasePool(function() {
            this.query('SELECT date(birthdate) FROM ICM_Contact WHERE ICM_contact_id = ? LIMIT 1', [id], function(err, rows, fields) {
                console.log(rows[0]);
                callback(null, ICM.contact.revive(rows[0]));
            })
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但是日期仍作为日期时间返回。

tia*_*anz 7

之所以返回完整的datetime而不是仅返回日期,是因为节点mysql模块将所有mysql date / datetime数据类型都转换为JavaScript Date对象。替代公认的解决方案,可以通过在连接中设置dateStrings为来关闭此功能true

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'mydb',
    port: '3306',
    ...
    dateStrings: true
});
Run Code Online (Sandbox Code Playgroud)


Qua*_*yen 4

你尝试过这个吗?

property: {
    get: function(id, callback) {
        mysql.DatabasePool(function() {
            this.query('SELECT DATE_FORMAT(birthdate,\'%m-%d-%Y\') FROM ICM_Contact WHERE ICM_contact_id = ? LIMIT 1', [id], function(err, rows, fields) {
                console.log(rows[0]);
                callback(null, ICM.contact.revive(rows[0]));
            })
       });
    }
}
Run Code Online (Sandbox Code Playgroud)