Google Apps Script, JDBC and MySQL does not work with Date 0000-00-00

别等时光非礼了梦想. 提交于 2021-02-18 19:09:50

问题


I am trying to read a MySQL db record using this simple code in Google Apps Script:

function testConn(){

  // make the connection
  var connection = Jdbc.getConnection("jdbc:mysql://" + DB.URL + ":" + DB.PORT + "/" + DB.DATABASE, DB.USERNAME, DB.PASSWORD);

  // perform the query
  var SQLstatement = connection.createStatement();
  var result = SQLstatement.executeQuery("SELECT date_available FROM oc_product where model = 'B23-U57-U57'");
  var colNum = result.getMetaData().getColumnCount();

  while(result.next()) {
    var res = {};
    for (var i=1; i<= colNum; i++) {
      var label = result.getMetaData().getColumnLabel(i);
      if (result.getMetaData().getColumnTypeName(i) == "DATE") {
        var val = result.getDate(i);
      } else {
        var val = result.getString(i);
      }
      res[label] = (val);
    }    
    Logger.log(JSON.stringify(res, null, 4));
  }
}

Because the date_available is "0000-00-00", this code throws error

Value '0000-00-00' can not be represented as

As suggested here I tried to use connection URL with parameter

?zeroDateTimeBehavior=convertToNull

But that also threw an error

The following connection properties are unsupported: zeroDateTimeBehavior.

What am I missing? Is this Google bug? Why this connection property is not supported? Is there any workaround apart of altering the SQL query?


回答1:


Not without altering SQL unfortunately. But for reference this is the way with altering the SQL:

I have used this recommendation: How to convert timestamp to datetime in MySQL?. And use the FROM_UNIXTIME() function in MySql. The only draw back was that a 0000-00-00 date will be imported in the spreadsheet as 1970-01-01 00:00:00.0 For me however this is not a problem at the moment.

Example:

var rs = stmt.executeQuery("SELECT `Subscriptions`.`SubscriptionId`,
  `Subscriptions`.`ItemId`, `Subscriptions`.`AccountId`,
  `Subscriptions`.`ContactId`,
  from_unixtime( unix_timestamp(TIMESTAMP( `Subscriptions`.`DateStart` ) ) ),
  from_unixtime( unix_timestamp(TIMESTAMP( `Subscriptions`.`DateEnd` ) ) ),
  `Subscriptions`.`AutoRenewal`,`Subscriptions`.`Invoice` from `Subscriptions`")



回答2:


I got around this issue by passing date twice, once converted to seconds and then the actual date value:

"SELECT TO_SECONDS(date_available), date_available FROM oc_product where model = 'B23-U57-U57'"

Next, check for the zero date and no include it in the result process:

var val;
var da = results.getDouble(1);  
if(da === 0) val = null;
else var = new Date(results.getString(2)); 


来源:https://stackoverflow.com/questions/33583012/google-apps-script-jdbc-and-mysql-does-not-work-with-date-0000-00-00

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!