Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save srugano/86e4e2113e8dbc4c6f8175ca868f557f to your computer and use it in GitHub Desktop.
Save srugano/86e4e2113e8dbc4c6f8175ca868f557f to your computer and use it in GitHub Desktop.
Google Cloud SQL Query in Sheets App Script
function connectToCloudSQL() {
var params = {
ip: "INSERT IP",
user: "INSERT USER",
password: "INSERT PASSWORD",
database: "INSERT DATABASE"
}
var dbUrl = 'jdbc:mysql://' + params.ip + '/' + params.database;
var conn = Jdbc.getConnection(dbUrl, params.user, params.password);
var stmt = conn.createStatement();
var sql = "desc mytable"; //WRITE YOUR QUERY HERE
stmt.setMaxRows(100);
var results = stmt.executeQuery(sql);
var mapping = {};
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a2');
var row = 0;
while (results.next()) {
for (var col = 0; col < results.getMetaData().getColumnCount(); col++) {
cell.offset(row, col).setValue(results.getString(col + 1));
}
row++;
}
while (results.next()) {
Logger.log(results.getString(1));
Logger.log(results.getString(2));
Logger.log(results.getString(3));
}
results.close();
stmt.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment