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 服务运行数据库:
- (推荐)使用 Jdbc.getCloudSqlConnection(url) 进行连接
- 使用 Jdbc.getConnection(url) 建立连接
下文介绍了这些方法。两者都有效 要求您授权一组 IP 范围访问您的数据库。
使用 Jdbc.getCloudSqlConnection(url)(推荐)
此方法使用 Jdbc.getCloudSqlConnection(url) 创建与 Google Cloud SQL MySQL 实例的连接
方法。数据库网址的格式为 jdbc:google:mysql://subname
,其中 subname
是 Google Cloud 控制台中 Cloud SQL 实例概览页面上列出的 MySQL 实例连接名称。
如需连接到 Cloud SQL SQL Server,请参阅 Jdbc.getConnection(url)。
使用 Jdbc.getConnection(url)
若要使用此方法,您必须授权特定的无类别域间路由 (CIDR) IP 地址范围,以便 Apps Script 的服务器能够连接到您的数据库。在运行脚本之前,请完成以下步骤:
授权这些 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
。
写入数据库
以下示例演示了如何将单个记录以及 500 个记录的批量写入数据库。批处理对于批量操作至关重要。
另请注意,使用了参数化语句,其中变量用 ?
表示。为防止
SQL 注入攻击
参数化语句来转义用户提供的所有数据。
从数据库读取
此示例演示了如何从 必要时循环遍历结果集。
关闭连接
脚本执行完毕后,JDBC 连接会自动关闭。(请注意,单次 google.script.run
调用会计为一次完整执行,即使发出调用的 HTML 服务页面保持打开状态也是如此。)
不过,如果您确定已完成的连接、语句或结果集
最好使用以下代码来手动关闭它们
JdbcConnection.close()
、
JdbcStatement.close()
,
或
JdbcResultSet.close()
。
显示提醒或提示对话框 还会终止所有打开的 JDBC 连接。不过,显示界面的 例如自定义菜单或对话框以及具有自定义功能的边栏 。
Google、Google Workspace 以及相关标志和徽标是 Google LLC。其他所有公司名和产品名是这些公司的商标 与之相关联的工具。