JDBC

Apps Script 可透過以下方式連線至外部資料庫: JDBC 服務,包裝標準 Java 資料庫連線技術。 JDBC 服務支援 MySQL 適用的 Google Cloud SQL、MySQL 和 Microsoft SQL 伺服器和 Oracle 資料庫

如要使用 JDBC 更新外部資料庫,指令碼必須開啟連線 然後傳送 SQL 陳述式進行變更。

Google Cloud SQL 資料庫

Google Cloud SQL 可讓您建立 執行基礎架構請注意,Cloud SQL 系統可能會根據您的使用情形向您收費

請按照下列步驟建立 Google Cloud SQL 執行個體: Cloud SQL 快速入門導覽課程

建立 Google Cloud SQL 連線

您可以透過兩種方式連線至 Google Cloud SQL 資料庫使用 Apps Script 的 JDBC 服務

這些方法的說明如下。兩者都有效,但第二種方法可以 您必須授權一組 IP 範圍來存取資料庫。

這個方法會使用 Jdbc.getCloudSqlConnection(url) 連線至 Google Cloud SQL MySQL 執行個體 方法。資料庫網址的格式為 jdbc:google:mysql://subname,其中 subname 是 MySQL 執行個體連線名稱 列在 Cloud SQL 執行個體的「總覽」頁面中, Google Cloud 控制台

如要連線至 Cloud SQL SQL Server,請參閱 Jdbc.getConnection(url)

使用 Jdbc.getConnection(url)

若要使用這個方法,您必須 無類別跨網域路由 (CIDR) IP 位址範圍,以便 Apps Script 的伺服器連線至您的資料庫。 執行指令碼之前,請先完成下列步驟:

  1. 在 Google Cloud SQL 執行個體中 授權 IP 範圍 一次一個項目。

  2. 複製指派給資料庫的網址;應包含 表單 jdbc:mysql:subname

授權這些 IP 範圍後,您就可以建立連至 Google Cloud SQL 執行個體 Jdbc.getConnection(url) 方法和您在上方複製的網址。

其他資料庫

如果您已有自己的 MySQL、Microsoft SQL Server 或 Oracle 資料庫, 可透過 Apps Script 的 JDBC 服務連線至這個 API。

建立其他資料庫連線

使用 Apps Script 建立資料庫連線 JDBC 服務,位於資料庫設定中 您必須授權來自這個資料來源的 IP 範圍。

建立這些許可清單後,即可與資料庫建立連線 方法是使用 Jdbc.getConnection(url) 以及資料庫的網址。

程式碼範例

下列程式碼範例假設您要連線至 Google Cloud SQL 資料庫。 並使用 Cloud Shell 指令列 Jdbc.getCloudSqlConnection(url) 方法。其他資料庫則必須使用 Jdbc.getConnection(url) 產生資料庫連線的方法。

如要進一步瞭解 JDBC 方法,請參閱 JDBC 的 Java 說明文件

建立資料庫、使用者和資料表

大多數開發人員都會使用 MySQL 指令列工具 建立資料庫、使用者和資料表不過您也可以這麼做 ,如下所示。建議您至少建立一個 這樣一來,指令碼就不一定需要 連線至資料庫 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 插入攻擊,則應使用 參數化陳述式,藉此逸出所有使用者提供的資料。

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);
  }
}

從資料庫讀取

這個範例示範如何從 並視需要循環處理結果集

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 連線就會自動關閉。(保留 但每個 google.script.run 就算呼叫了 通話保持開啟)。

不過,如果您確定自己已建立連線、陳述或結果集 建議您在指令碼結尾前呼叫 JdbcConnection.close()JdbcStatement.close(), 或 JdbcResultSet.close()

顯示快訊或提示對話方塊 也會終止所有開放的 JDBC 連線。但其他在顯示使用者介面 元素,例如自訂選單或對話方塊,以及含有自訂選項的側欄 而不是內容

Google、Google Workspace 與相關的符號及標誌皆為 Google LLC。所有其他公司和產品名稱均為該公司的商標 以及相關內容為何。