Tuesday, 26 November 2019

Add data to an SQL Table in Apps Script

The following code combines Google Apps Script and SQL to insert an ad-hoc entry (row of data) into an existing Table. This post follows on from this one for creating an SQL Table in Apps Script.

As before we begin by creating a statement for sending SQL code to the database. Then we can 'execute' the given SQL statement to 'insert into' the existing students Table the values provided.
var student = stmt.execute('INSERT INTO students'
                            + " VALUES ('456789', 'Donald', 'Duck', '9');"

                            );
4 values have been provided to match the 4 columns contained within the students Table:
  1. StudentNo - 456789
  2. FirstName - Donald
  3. LastName - Duck
  4. Shoesize - 9

// Database Credentials
var dbAddress = '';
var dbUser = '';
var dbPassword = '';
var dbName = '';
// connect to SQL database
var db = Jdbc.getConnection('jdbc:mysql://' + dbAddress + ':3306/' + dbName, dbUser, dbPassword);
function insertStudent() {
// create a statement to perform a task
var stmt = db.createStatement();
// insert a new student into existing students table
var student = stmt.execute('INSERT INTO students'
+ " VALUES ('456789', 'Donald', 'Duck', '9');"
);
// close connections after access
stmt.close();
db.close();
}
Add data to an SQL Table in Apps Script

No comments:

Post a Comment