Google Sheets – Connect with Database and Fetch Data to Google Spreadsheet

google sheetsgoogle-apps-script

I have been wondering about this for a while. We are using Google Spreadsheets a lot with my colleagues and the thing is that we always have to write down data that we already have in our MySQL database.

I wonder if there is a possibility to connect your spreadsheet with MySQL server and fetch the data to specific rows via executable script or something.

Best Answer

You can use the JDBC services of Google Apps Scripts.

You will have to write a script that populates your spreadsheet with data from the JDBC service.

Not sure exactly what you want to do, but you could start with the example from the documentation:

function foo() {
  var conn = Jdbc.getConnection('jdbc:mysql://<host>:3306/<instance>', 'user', 'password');
  var stmt = conn.createStatement();
  stmt.setMaxRows(100);
  var start = new Date();
  var rs = stmt.executeQuery('select * from person');

  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var cell = doc.getRange('a1');
  var row = 0;
  while (rs.next()) {
    for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
      cell.offset(row, col).setValue(rs.getString(col + 1));
    }
    row++;
  }
  rs.close();
  stmt.close();
  conn.close();
  var end = new Date();
  Logger.log('Time elapsed: ' + (end.getTime() - start.getTime()));
}