Google Apps Script 使用的是 JavaScript 语言;

在 Script 里使用 Jdbc.getCloudSqlConnectionJdbc.getConnection 来连接外部数据库,
参见 Google 提供的帮助:External Databases via JDBC

实例参考了 Git 上的语句;

连接数据库
  1. function myMySQLFetchData() {
  2. var conn = Jdbc.getConnection('jdbc:mysql://127.0.0.1:3306/employee_db', 'username', 'pass');
  3. var start = new Date(); // Get script starting time
  4. var stmt = conn.createStatement();
  5. stmt.setMaxRows(1000);// It sets the limit of the maximum nuber of rows in a ResultSet object
  6. var results = stmt.executeQuery('SELECT id,emp_name, emp_code FROM employee_details GROUP BY 1 LIMIT 1000');
  7. //change table name as per your database structure
  8. var doc = SpreadsheetApp.getActiveSpreadsheet('sheet1'); // 返回当前活动的电子表格
  9. var cell = doc.getRange('a1');
  10. var row = 0;
  11. var getCount = results.getMetaData().getColumnCount(); // Mysql table column name count.
  12. for (var i = 0; i < getCount; i++){
  13. cell.offset(row, i).setValue(rs.getMetaData().getColumnName(i+1)); // Mysql table column name will be fetch and added in spreadsheet.
  14. }
  15. var row = 1;
  16. while (rs.next()) {
  17. for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
  18. cell.offset(row, col).setValue(rs.getString(col + 1)); // Mysql table column data will be fetch and added in spreadsheet.
  19. }
  20. row++;
  21. }
  22. rs.close();
  23. stmt.close();
  24. conn.close();
  25. var end = new Date(); // Get script ending time
  26. Logger.log('Time elapsed: ' + (end.getTime() - start.getTime())); // To generate script log. To view log click on View -> Logs.
  27. }