Created
March 31, 2015 13:22
-
-
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/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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