Google Apps Script(GAS)で、Insert、Update、Deleteなどの更新系の処理を行うには、DBへのコネクションを行った後、ステートメントのオブジェクトを作成し、「.executeUpdte(‘Insert文など’)」 を実行する。実行結果は、0なら失敗、1以上なら成功(更新した行数が返るので1以上)となる。
サンプルコードは下記。
function myFunction() {
dbConnection();
}
// --------------------------------
// SSL 接続なしで接続する
// --------------------------------
function dbConnection(){
Logger.log('start dbConnection function.');
// 接続先設定
var connectionIp = 'xxx.xxx.xxx.xxx'; // 接続のMysqlのIPアドレス(ホスト名も可)
var userName = 'user'; // 接続で使うユーザ名
var passwd = 'password'; // 接続で使うパスワード
var databaseName = 'database'; // データベース名
var addr = 'jdbc:mysql://' + connectionIp + '/' + databaseName;
Logger.log('start mysql con');
Logger.log(addr);
var connectionInfo = {
user: userName,
password: passwd
}
// DBにコネクションをはる
var connection = Jdbc.getConnection(addr, connectionInfo);
Logger.log(connection.getCatalog());
// テーブルにInsertを行う処理
// sqlステートメントをデータベースに送信するためのオブジェクトを作る
var statement = connection.createStatement();
// Insert文を発行
var resultInsert = statement.executeUpdate('Insert Into List (id,listname) values ("5","kanagawa")');
// 実行結果が0なら失敗、1以上なら成功
Logger.log(resultInsert);
// ステートメントを閉じる
statement.close();
// テーブルにInsertを行う処理はここまで
// コネクションを閉じる
connection.close();
}