小编J. *_*lus的帖子

无法从Java连接到MySQL:MySQL驱动程序连接逻辑中的NullPointerException

我正在尝试连接到我在Java程序中使用MySQL创建的数据库,但它总是失败.

为了举例,这是我的代码:

import java.sql.*;

public class Squirrel {
    public static void main(String[] args) {
        String user;
        String password;
        Connection connection;
        Statement statement;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306", user, password);

            statement = connection.createStatement();

            // Other code
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我能够从IntelliJ中连接到数据库并添加mysql-connector-java-5.1.40.jar添加到项目中,但每次运行程序时都会DriverManager.getConnection()抛出:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: …
Run Code Online (Sandbox Code Playgroud)

java mysql

8
推荐指数
2
解决办法
7183
查看次数

标签 统计

java ×1

mysql ×1