JAVA中的Mysql连接失败

时间:2014-11-21 10:40:27

标签: java mysql eclipse

我正在使用eclipse和tomcat7。我确实导入了mysql jar文件,它位于tomcat文件夹中。 我尝试在我的页面上注册时遇到的错误:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mydb
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at connectionDb.openConnection(connectionDb.java:27)
    at connectionDb.getConnection(connectionDb.java:37)
    at DbManager.<clinit>(DbManager.java:7)
    at registrationServlet.doPost(registrationServlet.java:64)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Connection Opened
java.lang.NullPointerException

我的代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class connectionDb {

    private static connectionDb instance = null;

    private final String USERNAME = "root";
    private final String PASSWORD = "mypass";
    private final String CONN_STRING = "jdbc:mysql://localhost:3306/mydb";

    private Connection conn = null;

    private connectionDb() {
    }

    public static connectionDb getInstance() {
        if (instance == null) {
            instance = new connectionDb();
        }
        return instance;
    }

    private boolean openConnection() {
        try {
            conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }

    public Connection getConnection() {
        if (conn == null) {
            if (openConnection()) {
                System.out.println("Connection Opened");
                return conn;
            } else {
                return null;
            }
        }
        return conn;
    }
    public void close(){
        System.out.println("Close connection");
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        conn=null;
    }
}

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DbManager {

    private static Connection conn = connectionDb.getInstance().getConnection();

    public static void Insert(getset set) throws  ClassNotFoundException , SQLException {
        String driver = "com.mysql.jdbc.Driver";
        try {
            Class.forName(driver).newInstance();

            // insert username and password
            String sql = "INSERT INTO lonininfo(username, password) VALUES (?,?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, set.getUserName());
            pstmt.setString(2, set.getPassword());
            pstmt.executeUpdate();
            // insert user info
            String sql1 = "INSERT INTO userinfo(fullName, email, dateOfBirth, phoneNumber, companyName, companyEmail, paymentMethod) VALUES (?,?,?,?,?,?,?)";
            PreparedStatement pstmt1 = conn.prepareStatement(sql1);
            pstmt1.setString(1, set.getFullName());
            pstmt1.setString(2, set.getEmail());
            pstmt1.setString(3, set.getDateOfBirth());
            pstmt1.setString(4, set.getPhoneNumber());
            pstmt1.setString(5, set.getCompanyName());
            pstmt1.setString(6, set.getCompanyEmail());
            pstmt1.setString(7, set.getPaymentMethod());
            pstmt1.executeUpdate();
            connectionDb.getInstance().close();
        } catch (Exception e) {  
            System.out.println(e);  
        } finally {  
            if (conn != null) {  
                try {  
                    conn.close();  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }
}

4 个答案:

答案 0 :(得分:3)

可能在执行Class.forName(...)之前调用openConnection()。我尝试将此调用移至openConnection()方法而不是Insert()方法。

答案 1 :(得分:2)

必须首先加载驱动程序类,然后进行JDBC连接。在Class.forName方法中移动openConnection,如下所示,它应该有效。确保mysql驱动程序jar在类路径中。

private boolean openConnection() {
        try {
             String driver = "com.mysql.jdbc.Driver";
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }

答案 2 :(得分:2)

试试这个

  public class DbManager {

private static Connection conn;

public static void Insert(getset set) throws  ClassNotFoundException , SQLException {
    String driver = "com.mysql.jdbc.Driver";
    try {
        Class.forName(driver).newInstance();
        conn = connectionDb.getInstance().getConnection();
        // insert username and password
        String sql = "INSERT INTO lonininfo(username, password) VALUES (?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, set.getUserName());
        pstmt.setString(2, set.getPassword());
        pstmt.executeUpdate();
        // insert user info
        String sql1 = "INSERT INTO userinfo(fullName, email, dateOfBirth, phoneNumber, companyName, companyEmail, paymentMethod) VALUES (?,?,?,?,?,?,?)";
        PreparedStatement pstmt1 = conn.prepareStatement(sql1);
        pstmt1.setString(1, set.getFullName());
        pstmt1.setString(2, set.getEmail());
        pstmt1.setString(3, set.getDateOfBirth());
        pstmt1.setString(4, set.getPhoneNumber());
        pstmt1.setString(5, set.getCompanyName());
        pstmt1.setString(6, set.getCompanyEmail());
        pstmt1.setString(7, set.getPaymentMethod());
        pstmt1.executeUpdate();
        connectionDb.getInstance().close();
    } catch (Exception e) {  
        System.out.println(e);  
    } finally {  
        if (conn != null) {  
            try {  
                conn.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}

}

答案 3 :(得分:1)

从错误堆栈跟踪中,您似乎首先调用 openConnection 方法。您的 Class.forName(驱动程序)调用位于插入方法中。所以在加载类之前,你试图打开连接。 所以请移动 Class.forName(驱动程序)并将其放在可以在 openConnection 之前调用它的地方之外。每次插入或任何数据库操作调用之前,您都不需要每次都调用 Class.forName(驱动程序)