JDBC

Apps Script は、 JDBC サービス: 標準の JDBC のラッパー Java Database Connectivity テクノロジー。 JDBC サービスは Google Cloud SQL for MySQL、MySQL、Microsoft SQL をサポートしています。 2 つのデータベースがあります

JDBC を使用して外部データベースを更新するには、スクリプトで接続を開く必要があります SQL ステートメントを送信して変更を加えることができます。

Google Cloud SQL データベース

Google Cloud SQL では、既存のリレーショナル データベースを Google のクラウド上で実行しなお、Cloud SQL 使用量に応じて課金される可能性があります。

Google Cloud SQL インスタンスを作成するには、 Cloud SQL クイックスタート

Google Cloud SQL 接続の作成

Google Cloud SQL との接続を確立するには 2 つの方法があります。 Apps Script の JDBC サービスを使用して、データベースに接続します。

以下では、これらの方法について説明します。どちらも有効ですが、2 つ目の方法は データベースにアクセスするための一連の IP 範囲を承認する必要があります。

このメソッドは、Jdbc.getCloudSqlConnection(url) を使用して Google Cloud SQL MySQL インスタンスへの接続を作成します。 メソッドを呼び出します。データベースの URL の形式は jdbc:google:mysql://subname です。ここで、subname は MySQL インスタンス接続名です。 Cloud SQL インスタンスの [概要] ページに Google Cloud コンソール

Cloud SQL SQL Server に接続するには、Jdbc.getConnection(url) をご覧ください。

Jdbc.getConnection(url) を使用する

この方法を使用するには、 クラスレス ドメイン間ルーティング(CIDR) Apps Script のサーバーがデータベースに接続できるようにするための IP アドレス範囲。 スクリプトを実行する前に、次の手順を行います。

  1. Google Cloud SQL インスタンスで IP 範囲を承認する このデータソースから 1 つずつ取得します。

  2. データベースに割り当てられた URL をコピーします。が フォーム jdbc:mysql:subname

これらの IP 範囲を承認したら、VPC ネットワーク内の Google Cloud SQL インスタンスに Jdbc.getConnection(url) 先ほどコピーした URL を入力します。

その他のデータベース

すでに独自の MySQL、Microsoft SQL Server、Oracle データベースがある場合は、 Apps Script の JDBC サービスを介して接続できます。

他のデータベース接続の作成

Apps Script を使用してデータベース接続を作成するには、 データベース設定の JDBC サービス このデータソースの IP 範囲を承認する必要があります。

これらの許可リストを設定したら、データベースへの接続を作成できます。 いずれかを使用 Jdbc.getConnection(url) メソッドとデータベースの URL を使用します。

サンプルコード

以下のサンプルコードは、Google Cloud SQL データベースに接続していることを前提としています。 使用してデータベース接続を作成します。 Jdbc.getCloudSqlConnection(url) メソッドを呼び出します。その他のデータベースの場合は、 Jdbc.getConnection(url) メソッドを使用してデータベース接続を作成します。

JDBC メソッドについて詳しくは、このモジュールの JDBC の Java ドキュメント

データベース、ユーザー、テーブルを作成する

ほとんどのデベロッパーは MySQL コマンドライン ツールを使用して、 データベース、ユーザー、テーブルを作成できます。同じことを それを Apps Script に置く必要があります。少なくとも 1 つ作成することをおすすめします。 データベースに接続する必要はありません。 root

service/jdbc.gs
/**
 * Create a new database within a Cloud SQL instance.
 */
function createDatabase() {
  try {
    const conn = Jdbc.getCloudSqlConnection(instanceUrl, root, rootPwd);
    conn.createStatement().execute('CREATE DATABASE ' + db);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * Create a new user for your database with full privileges.
 */
function createUser() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, root, rootPwd);

    const stmt = conn.prepareStatement('CREATE USER ? IDENTIFIED BY ?');
    stmt.setString(1, user);
    stmt.setString(2, userPwd);
    stmt.execute();

    conn.createStatement().execute('GRANT ALL ON `%`.* TO ' + user);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * Create a new table in the database.
 */
function createTable() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
    conn.createStatement().execute('CREATE TABLE entries ' +
      '(guestName VARCHAR(255), content VARCHAR(255), ' +
      'entryID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(entryID));');
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

データベースに書き込む

以下の例は、単一のレコードをデータベースに書き込む方法を示しています。 500 件のレコードのバッチです一括処理は一括操作に不可欠です。

また、パラメータ化されたステートメントを使用していることにも注意してください。このステートメントでは、変数が ? で示されます。防ぐ方法 SQL インジェクション攻撃に対応するには、SQL インジェクション パラメータ化ステートメントを使用して、ユーザー提供データをすべてエスケープします。

service/jdbc.gs
/**
 * Write one row of data to a table.
 */
function writeOneRecord() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);

    const stmt = conn.prepareStatement('INSERT INTO entries ' +
      '(guestName, content) values (?, ?)');
    stmt.setString(1, 'First Guest');
    stmt.setString(2, 'Hello, world');
    stmt.execute();
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * Write 500 rows of data to a table in a single batch.
 */
function writeManyRecords() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
    conn.setAutoCommit(false);

    const start = new Date();
    const stmt = conn.prepareStatement('INSERT INTO entries ' +
      '(guestName, content) values (?, ?)');
    for (let i = 0; i < 500; i++) {
      stmt.setString(1, 'Name ' + i);
      stmt.setString(2, 'Hello, world ' + i);
      stmt.addBatch();
    }

    const batch = stmt.executeBatch();
    conn.commit();
    conn.close();

    const end = new Date();
    console.log('Time elapsed: %sms for %s rows.', end - start, batch.length);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

データベースから読み取る

この例では、Cloud Storage バケットから多数のレコードを読み取る方法を 必要に応じて結果セットをループします。

service/jdbc.gs
/**
 * Read up to 1000 rows of data from the table and log them.
 */
function readFromTable() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
    const start = new Date();
    const stmt = conn.createStatement();
    stmt.setMaxRows(1000);
    const results = stmt.executeQuery('SELECT * FROM entries');
    const numCols = results.getMetaData().getColumnCount();

    while (results.next()) {
      let rowString = '';
      for (let col = 0; col < numCols; col++) {
        rowString += results.getString(col + 1) + '\t';
      }
      console.log(rowString);
    }

    results.close();
    stmt.close();

    const end = new Date();
    console.log('Time elapsed: %sms', end - start);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

接続を閉じる

スクリプトの実行が完了すると、JDBC 接続は自動的に終了します。( 1 つの google.script.run が 呼び出しを行った HTML サービス ページが 通話はオープンのままになります)。

それでも、接続、ステートメント、結果セットが完了したことがわかっている場合は 手動で終了することをおすすめします。それには、 JdbcConnection.close() JdbcStatement.close(), または JdbcResultSet.close()

アラートまたはプロンプト ダイアログの表示 開いている JDBC 接続も終端します。一方で その他の表示 UI は カスタム メニューやダイアログ、サイドバーなどのカスタム 含まれません。

Google、Google Workspace、および関連するマークとロゴは、 Google LLC.その他すべての社名および製品名は、各社の商標です。 。