【问题标题】:Trying to connect java program to mySQL server尝试将 java 程序连接到 mySQL 服务器
【发布时间】:2017-05-14 15:03:44
【问题描述】:

当我尝试运行此代码时,我收到一条错误消息,提示我缺少正确的驱动程序,但当我下载驱动程序时,错误仍然发生。

public static void main(String[] args)
{
    try {
        Connection con = DriverManager.getConnection("108.167.137.42" ,"********", "********" );
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println( e.getMessage( ) );
    }
}

【问题讨论】:

  • 需要使用class.forName()加载jdbc驱动。参考本教程javatpoint.com/example-to-connect-to-the-mysql-database
  • 您需要mySql的驱动,请加载驱动。如果您遇到困难,可以在 google 上找到大量样板代码来执行此操作。
  • 如果您想远程连接到数据库,请确保使用提供的参数可以从外部访问它。
  • Connection con = DriverManager.getConnection("jdbc:mysql://108.167.137.42",...);

标签: java mysql jdbc


【解决方案1】:

网址不应仅包含 IP 地址,它应如下所示:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]]

所以你必须使用:

jdbc:mysql://108.167.137.42:3306/bd_name

read more here

【讨论】:

    【解决方案2】:

    对于 MySQL,JDBC 连接字符串应该如下:

    String URL = "jdbc:mysql://108.167.137.42:3306/database_name";
    String USERNAME = "root";
    String PASSWORD = "root";
    Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
    

    除了建议的代码更改外,您可能还必须在 my.cnf 文件中进行以下更改,否则您将无法连接到 MySQL 数据库。

    bind-address = xx.xx.xx.xx
    

    更改此设置后,您需要重新启动 MySQL 服务。希望这会有所帮助!

    【讨论】:

    • bind-address 与连接有什么关系?
    • @dosdebug,OP 使用的是外部 IP 而不是平时!因此建议改变!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2019-05-13
    • 2016-12-03
    相关资源
    最近更新 更多