Google Apps Script 使用的是 JavaScript 语言;
在 Script 里使用 Jdbc.getCloudSqlConnection 或 Jdbc.getConnection 来连接外部数据库,
参见 Google 提供的帮助:External Databases via JDBC ;
实例参考了 Git 上的语句;
连接数据库
function myMySQLFetchData() {
var conn = Jdbc.getConnection('jdbc:mysql://127.0.0.1:3306/employee_db', 'username', 'pass');
var start = new Date(); // Get script starting time
var stmt = conn.createStatement();
stmt.setMaxRows(1000);// It sets the limit of the maximum nuber of rows in a ResultSet object
var results = stmt.executeQuery('SELECT id,emp_name, emp_code FROM employee_details GROUP BY 1 LIMIT 1000');
//change table name as per your database structure
var doc = SpreadsheetApp.getActiveSpreadsheet('sheet1'); // 返回当前活动的电子表格
var cell = doc.getRange('a1');
var row = 0;
var getCount = results.getMetaData().getColumnCount(); // Mysql table column name count.
for (var i = 0; i < getCount; i++){
cell.offset(row, i).setValue(rs.getMetaData().getColumnName(i+1)); // Mysql table column name will be fetch and added in spreadsheet.
}
var row = 1;
while (rs.next()) {
for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
cell.offset(row, col).setValue(rs.getString(col + 1)); // Mysql table column data will be fetch and added in spreadsheet.
}
row++;
}
rs.close();
stmt.close();
conn.close();
var end = new Date(); // Get script ending time
Logger.log('Time elapsed: ' + (end.getTime() - start.getTime())); // To generate script log. To view log click on View -> Logs.
}