Google Sheets Apps Script连接本地MySQL及API遇连接报错求助
Google Sheets Apps Script 连接本地MySQL的问题解决
一、JDBC连接失败
代码
var server = "localhost"; var port = "3306"; var dbName = "dictionary"; var username = "xxxxxx"; var password = "xxxxxx"; var url = "jdbc:mysql://"+server+":"+port+"/"+dbName; function readData() { console.log(url, username, password) var conn = Jdbc.getConnection(url, username, password); }
报错信息
jdbc:mysql://localhost:3306/dictionary xxxxxx xxxxxx
12:26:37 PM Error Exception: Failed to establish a database connection. Check connection string, username and password.
原因与解决
Apps Script运行在Google云端服务器,localhost指向的是Google服务器而非你的本地机器,云端无法直接访问本地MySQL。
解决步骤:
- 配置MySQL允许公网访问:将绑定IP改为0.0.0.0,在防火墙/路由器开放3306端口,JDBC连接地址替换为你的公网IP。
- 调整MySQL用户权限:执行
GRANT ALL ON dictionary.* TO 'xxxxxx'@'%' IDENTIFIED BY 'xxxxxx'; FLUSH PRIVILEGES;,允许该用户从任意IP连接。 - 安全提示:公网暴露数据库存在风险,建议使用SSH隧道、VPN,或迁移数据库至云服务(如Google Cloud SQL)。
二、本地API调用出现DNS错误
本地成功调用的JS代码
let response = await fetch(url, { method:"POST", headers:{'Content-Type': 'application/json'}, body:JSON.stringify({sqlline:this.sqlline}) } )
Apps Script调用代码
function apiTEST() { let url = 'http://localhost:4000/wordle/read'; let sqlline = 'select word from dictionary.gamewords;' all_data = "" var options = { 'method' : 'POST', 'header': {'Content-Type': 'application/json'}, 'payload' : JSON.stringify({sqlline:sqlline}) }; console.log("URL:", url, "OPTIONS:", options); let response = UrlFetchApp.fetch(url, options); console.log("RESPONSE:", response) if (response.ok) { all_data = response.json() console.log("Response JSON") console.log("ALL_DATA: ",all_data) } else { console.log("HTTP-Error:", response.status) } return }
报错信息
Exception: DNS error: http://localhost:4000/wordle/read
原因与解决
云端无法解析本地localhost,因为Apps Script运行在Google服务器,无法访问你本地机器的API服务。
解决步骤:
- 使用公网代理工具(如ngrok)将本地API暴露到公网,把调用URL替换为ngrok提供的公网地址(例如
https://xxxx-xx-xx-xx-xx.ngrok.io/wordle/read)。 - 确保本地防火墙允许外部访问该API端口,同时代理工具配置正确。
- 长期使用建议将API部署到云服务器,避免依赖本地机器保持在线。
内容的提问来源于stack exchange,提问作者99Valk
相关产品推荐
相关产品推荐

