# Connect to MySQL Data in Google Apps Script

**URL:** <https://community.cdata.com/t/connect-to-mysql-data-in-google-apps-script/51>\
**Category:** How-to with CData\
**Tags:** article, cloud, google, mysql\
**Created:** [March 20, 2023, 7:11pm UTC](https://community.cdata.com/t/connect-to-mysql-data-in-google-apps-script/51 "2023-03-20T19:11:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![anonymous](https://avatars.discourse-cdn.com/v4/letter/a/8491ac/32.png) [@anonymous](https://community.cdata.com/u/anonymous)\
**Post date:** [March 20, 2023, 7:11pm UTC](https://community.cdata.com/t/connect-to-mysql-data-in-google-apps-script/51/1 "2023-03-20T19:11:39Z")

</div>

_Use CData Connect Cloud to access MySQL data in Google Apps Script._

Google Apps Script gives you the ability to create custom functionality within your Google documents, including Google Sheets, Google Docs, and more. With CData Connect Cloud, you get a SQL Server interface for any of the 100+ sources supported by CData, including MySQL. The SQL Server protocol is natively supported through the JDBC service in Google Apps Script, so by utilizing Connect Cloud, you gain access to live MySQL data within your Google documents.

This article shows how to connect to MySQL in Connect Cloud and provides sample scripting for processing MySQL data in a Google Spreadsheet.

Our script only reads data from a specified table, but you can easily extend the script to incorporate update functionality.

## Connect to MySQL in Connect Cloud

CData Connect Cloud uses a straightforward, point-and-click interface to connect to data sources.

1. Log into Connect Cloud, click Connections and click&nbsp;&nbsp;Add Connection

2. Select “MySQL” from the Add Connection panel

3. Enter the necessary authentication properties to connect to MySQL.

4. Click&nbsp;&nbsp;Create & Test

5. Navigate to the Permissions tab in the Add MySQL Connection page and update the User-based permissions.

### Add a Personal Access Token

If you are connecting from a service, application, platform, or framework that does not support OAuth authentication, you can create a Personal Access Token (PAT) to use for authentication. Best practices would dictate that you create a separate PAT for each service, to maintain granularity of access.

1. Click on your username at the top right of the Connect Cloud app and click User Profile.

2. On the User Profile page, scroll down to the Personal Access Tokens section and click&nbsp;&nbsp;Create PAT.

3. Give your PAT a name and click&nbsp;&nbsp;Create.

4. The personal access token is only visible at creation, so be sure to copy it and store it securely for future use.

With the connection configured, you are ready to connect to MySQL data from Google Apps Script.

## Connect to MySQL Data with Apps Script

At this point, you should have configured a connection MySQL in Connect Cloud. All that is left new is to use Google Apps Script to access Connect Cloud and work with your MySQL data in Google Sheets.

In this section, you will create a script (with a menu option to call the script) to populate a spreadsheet with MySQL data. We have created a sample script and explained the different parts. You can view the raw script&nbsp;**[at the and of the article](https://www.cdata.com/kb/tech/mysql-cloud-apps-script.rst#gs_file)**.

### 1. Create an Empty Script

To create a script for your Google Sheet, click&nbsp; **Tools&nbsp;&nbsp;Script editor** &nbsp;from the Google Sheets menu:

### 2. Declare Class Variables

Create a handful of class variables to be available for any functions created in the script.

[view source](https://www.cdata.com/kb/tech/mysql-cloud-apps-script.rst#viewSource)

`//replace the variables in this block with real values as needed`

`var`&nbsp;`address = ``'tds.cdata.com:14333'``;`

`var`&nbsp;`user = ``'CONNECT_USER'``; ``// user@mydomain.com`

`var`&nbsp;`userPwd = ``'CONNECT_USER_PAT'``;`

`var`&nbsp;`db = ``'MySQL1'``;`

`var`&nbsp;`dbUrl = ``'jdbc:sqlserver://'`&nbsp;`+ address + ``';databaseName='`&nbsp;`+ db;`

### 3. Add a Menu Option

This function adds a menu option to your Google Sheet, allowing you to use the UI to call your function.

[view source](https://www.cdata.com/kb/tech/mysql-cloud-apps-script.rst#viewSource)

`function`&nbsp;`onOpen() {`

`var`&nbsp;`spreadsheet = SpreadsheetApp.getActive();`

`var`&nbsp;`menuItems = [`

`{name: ``'Write data to a sheet'``, functionName: ``'connectToMySQLData'``}`

`];`

`spreadsheet.addMenu(``'MySQL Data'``, menuItems);`

`}`

### 4. Write a Helper Function

This function is used to find the first empty row in a spreadsheet.

[view source](https://www.cdata.com/kb/tech/mysql-cloud-apps-script.rst#viewSource)

`/*`

`* Finds the first empty row in a spreadsheet by scanning an array of columns`

`* @return The row number of the first empty row.`

`*/`

`function`&nbsp;`getFirstEmptyRowByColumnArray(spreadSheet, column) {`

`var`&nbsp;`column = spreadSheet.getRange(column + ``":"`&nbsp;`+ column);`

`var`&nbsp;`values = column.getValues(); ``// get all data in one call`

`var`&nbsp;`ct = 0;`

`while`&nbsp;`( values[ct] && values[ct][0] != ``""`&nbsp;`) {`

`ct++;`

`}`

`return`&nbsp;`(ct+1);`

`}`

### 5. Write a Function to Write MySQL Data to a Spreadsheet

The function below writes the MySQL data, using the Google Apps Script JDBC functionality to connect to Connect Cloud, SELECT data, and populate a spreadsheet. When the script is run, two input boxes will appear:

The first one asks the user to input the name of a sheet to hold the data (if the spreadsheet does not exist, the function creates it).

The second asks the user to input the name of a MySQL table to read. If an invalid table is chosen, an error message appears and the function is exited.

Note, while the function is designed for use as a menu option, you can extend it for use as a spreadsheet formula.

[view source](https://www.cdata.com/kb/tech/mysql-cloud-apps-script.rst#viewSource)

`/*`

`* Reads data from a specified MySQL 'table' and writes it to the specified sheet.`

`*    (If the specified sheet does not exist, it is created.)`

`*/`

`function`&nbsp;`connectToMySQLData() {`

`var`&nbsp;`thisWorkbook = SpreadsheetApp.getActive();`

`//select a sheet and create it if it does not exist`

`var`&nbsp;`selectedSheet = Browser.inputBox(``'Which sheet would you like the data to post to?'``,Browser.Buttons.OK_CANCEL);`

`if`&nbsp;`(selectedSheet == ``'cancel'``)`

`return``;`

`if`&nbsp;`(thisWorkbook.getSheetByName(selectedSheet) == ``null``)`

`thisWorkbook.insertSheet(selectedSheet);`

`var`&nbsp;`resultSheet = thisWorkbook.getSheetByName(selectedSheet);`

`var`&nbsp;`rowNum = 2;`

`//select a MySQL 'table'`

`var`&nbsp;`table = Browser.inputBox(``'Which table would you like to pull data from?'``,Browser.Buttons.OK_CANCEL);`

`if`&nbsp;`(table == ``'cancel'``)`

`return``;`

`var`&nbsp;`name = Jdbc.getConnection(dbUrl, {`

`user: user,`

`password: userPwd`

`}  `

`);`

`//confirm that var table is a valid table/view`

`var`&nbsp;`dbMetaData = name.getMetaData();`

`var`&nbsp;`tableSet = dbMetaData.getTables(``null``, ``null``, table, ``null``);`

`var`&nbsp;`validTable = ``false``;`

`while`&nbsp;`(tableSet.next()) {`

`var`&nbsp;`tempTable = tableSet.getString(3);`

`if`&nbsp;`(table.toUpperCase() == tempTable.toUpperCase()){`

`table = tempTable;`

`validTable = ``true``;`

`break``;`

`}`

`}`

`tableSet.close();`

`if`&nbsp;`(!validTable) {`

`Browser.msgBox(``"Invalid table name: "`&nbsp;`+ table, Browser.Buttons.OK);`

`return``;`

`}`

`var`&nbsp;`stmt = name.createStatement();`

`var`&nbsp;`results = stmt.executeQuery(``'SELECT * FROM '`&nbsp;`+ table);`

`var`&nbsp;`rsmd = results.getMetaData();`

`var`&nbsp;`numCols = rsmd.getColumnCount();`

`//if the sheet is empty, populate the first row with the headers`

`var`&nbsp;`firstEmptyRow = getFirstEmptyRowByColumnArray(resultSheet, ``"A"``);`

`if`&nbsp;`(firstEmptyRow == 1) {`

`//collect column names`

`var`&nbsp;`headers = ``new`&nbsp;`Array(``new`&nbsp;`Array(numCols));`

`for`&nbsp;`(``var`&nbsp;`col = 0; col < numCols; col++){`

`headers[0][col] = rsmd.getColumnName(col+1);`

`}`

`resultSheet.getRange(1, 1, headers.length, headers[0].length).setValues(headers);`

`} ``else`&nbsp;`{`

`rowNum = firstEmptyRow;`

`}`

`//write rows of MySQL data to the sheet`

`var`&nbsp;`values = ``new`&nbsp;`Array(``new`&nbsp;`Array(numCols));`

`while`&nbsp;`(results.next()) {`

`for`&nbsp;`(``var`&nbsp;`col = 0; col < numCols; col++) {`

`values[0][col] = results.getString(col + 1);`

`}`

`resultSheet.getRange(rowNum, 1, 1, numCols).setValues(values);`

`rowNum++;`

`}`

`results.close();`

`stmt.close();`

`}`

When the function is completed, you have a spreadsheet populated with your MySQL data, and you can now leverage all of the calculating, graphing, and charting functionality of Google Sheets anywhere you have access to the Internet.

* * *

## Complete Google Apps Script

[view source](https://www.cdata.com/kb/tech/mysql-cloud-apps-script.rst#viewSource)

`//replace the variables in this block with real values as needed`

`var`&nbsp;`address = ``'tds.cdata.com:14333'``;`

`var`&nbsp;`user = ``'CONNECT_USER'``; ``// user@mydomain.com`

`var`&nbsp;`userPwd = ``'CONNECT_USER_PAT'``;`

`var`&nbsp;`db = ``'MySQL1'``;`

`var`&nbsp;`dbUrl = ``'jdbc:sqlserver://'`&nbsp;`+ address + ``';databaseName='`&nbsp;`+ db;`

`function`&nbsp;`onOpen() {`

`var`&nbsp;`spreadsheet = SpreadsheetApp.getActive();`

`var`&nbsp;`menuItems = [`

`{name: ``'Write table data to a sheet'``, functionName: ``'connectToMySQLData'``}`

`];`

`spreadsheet.addMenu(``'MySQL Data'``, menuItems);`

`}`

`/*`

`* Finds the first empty row in a spreadsheet by scanning an array of columns`

`* @return The row number of the first empty row.`

`*/`

`function`&nbsp;`getFirstEmptyRowByColumnArray(spreadSheet, column) {`

`var`&nbsp;`column = spreadSheet.getRange(column + ``":"`&nbsp;`+ column);`

`var`&nbsp;`values = column.getValues(); ``// get all data in one call`

`var`&nbsp;`ct = 0;`

`while`&nbsp;`( values[ct] && values[ct][0] != ``""`&nbsp;`) {`

`ct++;`

`}`

`return`&nbsp;`(ct+1);`

`}`

`/*`

`* Reads data from a specified 'table' and writes it to the specified sheet.`

`*    (If the specified sheet does not exist, it is created.)`

`*/`

`function`&nbsp;`connectToMySQLData() {`

`var`&nbsp;`thisWorkbook = SpreadsheetApp.getActive();`

`//select a sheet and create it if it does not exist`

`var`&nbsp;`selectedSheet = Browser.inputBox(``'Which sheet would you like the data to post to?'``,Browser.Buttons.OK_CANCEL);`

`if`&nbsp;`(selectedSheet == ``'cancel'``)`

`return``;`

`if`&nbsp;`(thisWorkbook.getSheetByName(selectedSheet) == ``null``)`

`thisWorkbook.insertSheet(selectedSheet);`

`var`&nbsp;`resultSheet = thisWorkbook.getSheetByName(selectedSheet);`

`var`&nbsp;`rowNum = 2;`

`//select a MySQL 'table'`

`var`&nbsp;`table = Browser.inputBox(``'Which table would you like to pull data from?'``,Browser.Buttons.OK_CANCEL);`

`if`&nbsp;`(table == ``'cancel'``)`

`return``;`

`var`&nbsp;`name = Jdbc.getConnection(dbUrl, {`

`user: user,`

`password: userPwd`

`}`

`);`

`//confirm that var table is a valid table/view`

`var`&nbsp;`dbMetaData = name.getMetaData();`

`var`&nbsp;`tableSet = dbMetaData.getTables(``null``, ``null``, table, ``null``);`

`var`&nbsp;`validTable = ``false``;`

`while`&nbsp;`(tableSet.next()) {`

`var`&nbsp;`tempTable = tableSet.getString(3);`

`if`&nbsp;`(table.toUpperCase() == tempTable.toUpperCase()){`

`table = tempTable;`

`validTable = ``true``;`

`break``;`

`}`

`}`

`tableSet.close();`

`if`&nbsp;`(!validTable) {`

`Browser.msgBox(``"Invalid table name: "`&nbsp;`+ table, Browser.Buttons.OK);`

`return``;`

`}`

`var`&nbsp;`stmt = name.createStatement();`

`var`&nbsp;`results = stmt.executeQuery(``'SELECT * FROM '`&nbsp;`+ table);`

`var`&nbsp;`rsmd = results.getMetaData();`

`var`&nbsp;`numCols = rsmd.getColumnCount();`

`//if the sheet is empty, populate the first row with the headers`

`var`&nbsp;`firstEmptyRow = getFirstEmptyRowByColumnArray(resultSheet, ``"A"``);`

`if`&nbsp;`(firstEmptyRow == 1) {`

`//collect column names`

`var`&nbsp;`headers = ``new`&nbsp;`Array(``new`&nbsp;`Array(numCols));`

`for`&nbsp;`(``var`&nbsp;`col = 0; col < numCols; col++){`

`headers[0][col] = rsmd.getColumnName(col+1);`

`}`

`resultSheet.getRange(1, 1, headers.length, headers[0].length).setValues(headers);`

`} ``else`&nbsp;`{`

`rowNum = firstEmptyRow;`

`}`

`//write rows of MySQL data to the sheet`

`var`&nbsp;`values = ``new`&nbsp;`Array(``new`&nbsp;`Array(numCols));`

`while`&nbsp;`(results.next()) {`

`for`&nbsp;`(``var`&nbsp;`col = 0; col < numCols; col++) {`

`values[0][col] = results.getString(col + 1);`

`}`

`resultSheet.getRange(rowNum, 1, 1, numCols).setValues(values);`

`rowNum++;`

`}`

`results.close();`

`stmt.close();`

`}`
