将JDBC连接到IP地址

时间:2018-11-02 20:28:41

标签: java mysql database jdbc

我在使用JDBC连接到外部IP地址时遇到问题。执行以下代码时,出现此错误No suitable driver found for jdbc:mysql://52.206.157.109:3306/U054Jk

代码:

package util;

import java.sql.*;

public class db {
    private static String server = "52.206.157.109";
    private static String dbName = "U054Jk";
    private static String userName = "secret";
    private static String password = "secret";

    private static Connection getCon() throws SQLException {
        String host = "jdbc:mysql://" + server + ":3306/" + dbName;

        Connection conn = DriverManager.getConnection(
                host,
                userName,
                password
        );

        return conn;
    }

    public static ResultSet ExecQuery(String query) throws SQLException {
        //Get the connection
        Connection conn = getCon();

        //Create the statement
        Statement stmt = conn.createStatement();

        //Execute the statement
        ResultSet rs = stmt.executeQuery(query);

        //Return ResultSet
        return rs;
    }
}

我可以使用凭据很好地连接我的SQL客户端,但不能完全确定URL所需的JDBC字符串。谢谢您的帮助。

1 个答案:

答案 0 :(得分:3)

请在类路径中添加MySQL Connector。您的项目需要JDBC driver来实现interfacesJDBC

如果您使用的是Apache Maven,请在pom中添加以下内容。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.13</version>
</dependency>

否则,请从link下载jar并将其添加到类路径。