问题
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