无法通过应用程序脚本(JDBC)连接到本地MySQL服务器

2022-02-24 00:00:00 google-apps-script localhost mysql jdbc

请查看下面的编辑内容,我将把原始问题留给帮助他人。

我试图通过Apps脚本和JDBC连接到本地MySQL服务器,但我不断收到两个错误中的一个。此代码:

function connectTest() {
  var conn = Jdbc.getConnection("jdbc:mysql://localhost", "root", "xxx");
}

给出错误Failed to establish a database connection. Check connection string, username and password.

此代码:

function connectTest() {
  var conn = Jdbc.getConnection("jdbc:mysql://localhost:3306", "xxx", "pass");
}

给出错误Invalid argument: url

我已经尝试了几十种组合,但都不能奏效。从Apps Scripts登录的尝试不会显示在MySQL的访问日志中(即,如果我尝试使用错误的信息在本地登录,我会看到[Note] Access denied for user 'host'@'localhost' (using password: YES))。我已向root授予适当的访问权限:

mysql> show grants for 'root'@'%';
+-------------------------------------------------------------+
| Grants for root@%                                           |
+-------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION |
+-------------------------------------------------------------+
1 row in set (0.00 sec)

要将本地数据库公开给Internet/Google Apps脚本,还需要执行其他操作吗?

编辑:

我现在可以从MySQL日志中收到拒绝访问的通知(例如Access denied for user 'root'@'12.123.12.123' (using password: YES)),但应用程序仍然无法连接。我尝试用我的公网IP添加bind-address,但是MySQL无法启动,我得到([ERROR] Can't start server: Bind on TCP/IP port: Can't assign requested address)

function connectTest() {
  var conn = Jdbc.getConnection("jdbc:mysql://12.123.12.123:3306", "root", "xxx");
}
EDIT2:我更改了bind-address=0.0.0.0,这确实允许我在数据库日志中收到拒绝访问错误,但仍然没有成功连接。我已成功连接到Internet上其他打开的MySQL数据库(例如,ensembldb.ensembl.org:3306),但仍然无法连接到本地数据库。


解决方案

终于拿到了,我是这样让它工作的:

  1. 使用编辑my.cnf(此文件可以位于多个不同位置,甚至可能不存在,我将我的文件放在此处/usr/local/etc/

    [mysqld]
    bind-address=0.0.0.0
    skip-host-cache
    skip-name-resolve
    
  2. 将端口3306开放到互联网(对于Xfinity,这意味着进入http://10.0.0.1/单击左侧的"高级">底部的"端口转发">"添加设备",找到运行MySQL的设备,然后单击"添加")

  3. 在MySQL和FLUSH PRIVILEGES;中授予相应权限。您可以使用GRANT ALL PRIVILEGES ON *.* TO <USER>@'%' IDENTIFIED BY '<PASSWORD>'来完成此操作,但这允许任何IP,下面的Python脚本将授予Google的IP。您应该根据Google的JDBC文档检查此IP列表。

    from sqlalchemy import create_engine, MetaData
    
    conString = 'mysql+pymysql://<USER>:<PASSWORD>@localhost:3306/<DB>'
    mysql = create_engine(conString)
    
    ips = ['64.18.0.0 - 64.18.15.255',
    '64.233.160.0 - 64.233.191.255',
    '66.102.0.0 - 66.102.15.255',
    '66.249.80.0 - 66.249.95.255',
    '72.14.192.0 - 72.14.255.255',
    '74.125.0.0 - 74.125.255.255',
    '173.194.0.0 - 173.194.255.255',
    '207.126.144.0 - 207.126.159.255',
    '209.85.128.0 - 209.85.255.255',
    '216.239.32.0 - 216.239.63.255']
    
    for ip in ips:
        ip2 = ip.replace(' - ', '/')
        try:
            sql = "CREATE USER '<USER>'@'" + ip2 + "' identified by '<PASSWORD>';"
            mysql.execute(sql)
        except:
            print ip2
        sql = "GRANT ALL PRIVILEGES ON <DB>.* TO '<USER>'@'" + ip2 + "';"
        mysql.execute(sql)
    

相关文章