繁体   English   中英

无法将Java连接到MySQL

[英]Unable to connect Java to MySQL

我正在使用Eclipse将Java应用程序连接到MYSQL(XAMPP)

ConnecttoMsql.java

public void openConnection() throws SQLException{

        Connection connection = null;
        Statement statement = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysqltest","root","");
            if (connection != null) {
                System.out.println ("Connected may be?");
                connection.close();
            }
            else {
                System.out.println ("Not connected?");
            }
        }
        catch (Exception e) {
            connection.close();
        }
    }

当我尝试用servlet调用它时:

try {
        connectMySQL.openConnection();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

它说

java.lang.NullPointerException
    com.dynamicfyp.pkg.ConnecttoMsql.openConnection(ConnecttoMsql.java:39)
    com.dynamicfyp.pkg.ConnecttoMysqlServlet.doGet(ConnecttoMysqlServlet.java:35)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

怎么了 ?

如果驱动程序不在类路径上,则将在openConnection()抛出ClassNotFoundException但是在catch()您在null连接上引用connection.close() -抛出NullPointerException

如果发生这种情况,则需要将mysql-connector.jar添加到您的WEB-INF / LIB中

在您的catch块中尝试此代码

   catch (Exception e) {
    if(connection!=null)    
    connection.close();
    }

现在您将不会遇到nullpointer异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM