如何使用应用程序脚本从 mysql 添加到电子表格

How to add from mysql to spreadsheet with app script

我想使用 google 应用程序脚本将来自 mysql 的数据添加到传播 sheet。 并且已经成功拉取数据并成功显示在控制台日志中,但是如何进入googlesheet???

这是脚本:

var server = 'xxx.xxx.xxx.xxx';
var port = 3306;
var dbName = 'xxx';
var username = 'xxx';
var password = 'xxxxx';
var url = 'jdbc:mysql://'+server+':'+port+'/'+dbName;
 
function readFromTable() {
  try {
    const conn = Jdbc.getConnection(url, username, password);
    const start = new Date();
    const stmt = conn.createStatement();
    stmt.setMaxRows(1000);
    const results = stmt.executeQuery('SELECT * FROM tickets');
    const numCols = results.getMetaData().getColumnCount();

    while (results.next()) {
      let rowString = '';
      for (let col = 0; col < numCols; col++) {
        rowString += results.getString(col + 1) + '\t';
      }
      Logger.log(rowString); 
      **//here should be a script to input data into google sheet**
    }

    results.close();
    stmt.close();

    const end = new Date();
    Logger.log('Time elapsed: %sms', end - start);
  } catch {
    // TODO(developer) - Handle exception from the API
    Logger.log('Failed with an error %s', err.message);
  }
}

像这样:

function readFromTable() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  try {
    const conn = Jdbc.getConnection(url, username, password);
    const start = new Date();
    const stmt = conn.createStatement();
    stmt.setMaxRows(1000);
    const results = stmt.executeQuery('SELECT * FROM tickets');
    const numCols = results.getMetaData().getColumnCount();
    let a = [];
    while (results.next()) {
      let row = [];
      for (let col = 0; col < numCols; col++) {
        row.push(results.getString(col + 1));
      }
      a.push(row);
      
    }
    sh.getRange(1,1,a.length,a[0].length).setValues(a);
    results.close();
    stmt.close();

    const end = new Date();
    Logger.log('Time elapsed: %sms', end - start);
  } catch {
    // TODO(developer) - Handle exception from the API
    Logger.log('Failed with an error %s', err.message);
  }
}