我正在尝试使用Google App Script将数据添加到我的Google Cloud SQL数据库中。昨晚我完成时我的代码工作正常,但是当我今天早上运行它时,它现在给我错误"由于超时或客户端请求而取消语句",我在云控制台中遇到的错误是"读取通信数据包时出错"。
昨晚它正在处理大约1,600行数据。我已经玩过它并缩小了范围,当有更多的 15 行时会发生错误。15 行它将添加数据,将其更改为 16 行并抛出错误,这告诉我这不是连接本身。我还通过将第 15 行复制到第 16 行并删除所有其他数据来测试电子表格中的数据,这不起作用。我对我读到的所有内容的主要困惑是,它正在超时,昨晚它在 1,600 行数据中工作正常。我的代码如下:
function connection(folderId, db, c1, c2, c3, c4, c5, c6, c7) {
var files = DriveApp.getFolderById(folderId).getFiles();
var excelfile = files.next();
var fileId = excelfile.getId();
var data = SpreadsheetApp.openById(fileId).getSheetByName('Report 1');
var last = data.getLastRow()
var sheetdata=data.getRange("B5:H16").getValues();
var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);//dburl is not defined
conn.setAutoCommit(false);
var start = new Date();
var stmt = conn.prepareStatement('INSERT INTO '+ db + ' ' + '('+c1+','+c2+','+c3+','+c4+','+c5+','+c6+','+c7+') values (?, ?, ?, ?, ?, ?, ?)');
for (var i=0; i<sheetdata.length; i++) {
stmt.setString(1, Utilities.formatDate(sheetdata[i][0], 'Etc/GMT', 'yyyy-MM-dd'));
stmt.setString(2, sheetdata[i][1]);
stmt.setString(3, sheetdata[i][2]);
stmt.setString(4, sheetdata[i][3]);
stmt.setString(5, sheetdata[i][4]);
stmt.setString(6, sheetdata[i][5]);
stmt.setString(7, sheetdata[i][6]);
stmt.addBatch();
}
var batch = stmt.executeBatch();
conn.commit();
conn.close();
var end = new Date()
Logger.log('Time elapsed: %sms for %s rows.', end - start, batch.length);
}
发现问题出在新的应用脚本运行时 V8 上。要解决此问题,请将运行时更改回 Rhino。为此,请转到"查看>显示项目清单",然后在显示"运行时版本"的位置:"V8"将其更改为"运行时版本":"稳定"。目前这里有一个关于这个问题的未决错误:https://issuetracker.google.com/issues/149413841
像这样尝试:
function connection(folderId, db, c1, c2, c3, c4, c5, c6, c7) {
var ss=SpreadsheetApp.openById("fileId");//just go to the file and get the id
var sh=ss.getSheetByName('Report 1');
var rg=sh.getRange("B5:H16");
var sheetdata=rg.getValues();
var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);//dburl is not defined
conn.setAutoCommit(false);
var stmt = conn.prepareStatement('INSERT INTO '+ db + ' ' + '('+c1+','+c2+','+c3+','+c4+','+c5+','+c6+','+c7+') values (?, ?, ?, ?, ?, ?, ?)');
for (var i=0; i<sheetdata.length; i++) {
stmt.setString(1, Utilities.formatDate(sheetdata[i][0], Session.getScriptTimeZone(), 'yyyy-MM-dd'));
stmt.setString(2, sheetdata[i][1]);
stmt.setString(3, sheetdata[i][2]);
stmt.setString(4, sheetdata[i][3]);
stmt.setString(5, sheetdata[i][4]);
stmt.setString(6, sheetdata[i][5]);
stmt.setString(7, sheetdata[i][6]);
stmt.addBatch();
}
var batch = stmt.executeBatch();
conn.commit();
conn.close();
}