通过JDBC将MySQL表数据提取到gsheet

时间:2018-01-18 02:15:22

标签: mysql jdbc google-apps-script

我正在尝试从mySQL表中提取数据并将其填充到gsheet中。我写了下面的脚本,但我在第50行给出了一个错误“无法将数组转换为对象”。我确定这是一个二维数组。我确定我错过了一些显而易见的东西,因为这是我的第一个剧本。

function readFromTable() {
  var ss = SpreadsheetApp.getActive();
  var sheetDetails = ss.getSheetByName('Details');
  var sheetData = ss.getSheetByName('Data');
  var host = sheetDetails.getRange("B1").getValue();
  var databaseName = sheetDetails.getRange("B2").getValue();
  var userName = sheetDetails.getRange("B3").getValue();
  var password = sheetDetails.getRange("B4").getValue();
  var port = sheetDetails.getRange("B5").getValue();
  var tableName = sheetDetails.getRange("B6").getValue();

  var url = 'jdbc:mysql://'+host+':'+port+'/'+databaseName;
  var sql = 'SELECT * FROM ' + tableName;
  try{

    var connection = Jdbc.getConnection(url, userName, password);

    var results = connection.createStatement().executeQuery(sql);
    var metaData = results.getMetaData();
    var columns = metaData.getColumnCount();

    //Retrieve metaData to a 2D array
    var values = [];
    var value = [];
    var element = '';

    //Get table headers
    for(i = 1; i <=columns; i ++){
      element = metaData.getColumnLabel(i);
      value.push(element);
    }
    values.push(element);

    //Get table data row by row
    while(results.next()){
      value = [];
      for(i = 1; i <= columns; i ++){
        element = results.getString(i)
        value.push(element);
      }
      values.push(value);
    }


    //Close connection
    results.close();

    //Write data to sheet Data
    sheetData.clear();
    sheetData.getRange(1, 1, values.length, value.length).setValues(values);
    SpreadsheetApp.getActive().toast('Your data has been refreshed');
  }catch(err){
    SpreadsheetApp.getActive().toast(err.message);
  }
}

0 个答案:

没有答案