Skip to content

Instantly share code, notes, and snippets.

@IronistM
Created March 31, 2015 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IronistM/679230e55ac4f5c4ac2a to your computer and use it in GitHub Desktop.
Save IronistM/679230e55ac4f5c4ac2a to your computer and use it in GitHub Desktop.
A function to connect to a database using Google Apps and viewing data in Google Sheets (source : http://www.mousewhisperer.co.uk/drivebunny/connecting-to-mysql-databases-using-apps-script/)
function connect_to_DB() {
// make the connection
var connection = Jdbc.getConnection("jdbc:mysql://[database URL or IP]:[port number]/[database name]", "[user name]", "[password]");
// perform the query
var SQLstatement = connection.createStatement();
var result = SQLstatement.executeQuery("SELECT * FROM users");
// choose a range in sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange('A2');
// loop through result object, setting cell values to database data
var row = 0;
while(result.next()) {
for(var i=0; i<4; i++) { // four fields per record
cell.offset(row, i).setValue(result.getString(i+1));
}
row++;
}
// tidy up
result.close();
SQLstatement.close();
connection.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment