通过jdbc将mysql表数据拉入gsheet

z9zf31ra  于 2021-06-21  发布在  Mysql
关注(0)|答案(0)|浏览(232)

我试图从mysql表中提取数据并将其填充到gsheet中。我已经编写了下面的脚本,但是在第50行“cannotconvertary to object”出现了一个错误。我肯定这是一个二维阵列。不过,我肯定我遗漏了一些明显的东西,因为这是我的第一个剧本。

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);
  }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题