JDBC

Apps 脚本可以通过 JDBC 服务,这是标准的 Java 数据库连接技术。 JDBC 服务支持 Google Cloud SQL for MySQL、MySQL、Microsoft SQL 服务器数据库和 Oracle 数据库。

如需使用 JDBC 更新外部数据库,您的脚本必须打开一个连接 发送到数据库,然后通过发送 SQL 语句进行更改。

Google Cloud SQL 数据库

借助Google Cloud SQL,您可以创建 存储于 Google 云端请注意,Cloud SQL 可能会产生基于您的用量的费用。

您可以按照 Cloud SQL 快速入门

创建 Google Cloud SQL 连接

您可以通过两种方式与 Google Cloud SQL 建立连接 使用 Apps 脚本的 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) Apps 脚本的服务器可以连接到您的数据库的 IP 地址范围。 在运行脚本之前,请完成以下步骤:

  1. 在您的 Google Cloud SQL 实例中 为 IP 范围授权 每次一个来自此数据源的数据。

  2. 复制分配给您的数据库的网址;它应该包含 表单 jdbc:mysql:subname

授权这些 IP 范围后,您就可以创建 使用 Jdbc.getConnection(url) 方法和您在上面复制的网址。

其他数据库

如果您已有自己的 MySQL、Microsoft SQL Server 或 Oracle 数据库, 可以通过 Apps 脚本的 JDBC 服务连接到它。

创建其他数据库连接

要使用 Apps 脚本创建数据库连接 JDBC 服务,位于数据库设置中 您必须为来自此数据源的 IP 范围授权。

这些许可名单准备就绪后,您就可以创建与数据库的连接 使用 Jdbc.getConnection(url) 方法和数据库的网址。

示例代码

以下示例代码假定您要连接到 Google Cloud SQL 数据库, 并使用 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。其他所有公司名和产品名是这些公司的商标 与之相关联的工具。