用Java连接Java

时间:2014-12-18 23:26:25

标签: java mysql jdbc

我正在尝试将Neteans Java项目与Mysql数据库连接,我无法建立连接,我不知道可能出现什么问题

我的Java代码:

private void setupLoginEventListener() {
        loginBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                rightFirstText = userName.getText();
                rightText = password.getPassword();
                if (rightFirstText.isEmpty() && rightText.length == 0) {
                    JOptionPane.showMessageDialog(JavaApplication6.this, "All fields are required", "Error", JOptionPane.ERROR_MESSAGE);
                } else if (rightText.length == 0) {
                    JOptionPane.showMessageDialog(JavaApplication6.this, "Password is required", "Error", JOptionPane.ERROR_MESSAGE);
                } else {

                    try {
                        conn = getDBConnection();
                        pst = conn.prepareStatement("select * from pdie where username =? and password=?");
                        pst.setString(1, rightFirstText);
                        pst.setString(2, new String(rightText));
                        rs = pst.executeQuery();
                        while (rs.next()) {
                            JOptionPane.showMessageDialog(JavaApplication6.this, "Login Successfull");
                        } 
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(JavaApplication6.this, "Login Failed");
                    }
                }
            }
        });
    }

    public Connection getDBConnection() {
        Connection con = null;
        String url = "jdbc:mysql://localhost:3536/";
        String dbName = "projectdb";
        String driver = "com.mysql.jdbc.Driver";
        String connectUserName = "root";
        String connectPassword = "";
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + dbName, connectUserName, connectPassword);
            System.out.println("CONNECTION ESTABLISHED.");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("CONNECTION COULD NOT BE ESTABLISHED.");
        }
        return con;
    }

任何想法?

它在此行中为空指针异常提供了错误

pst = conn.prepareStatement("select * from pdie where username =? and password=?");

1 个答案:

答案 0 :(得分:0)

输入这些行

        st=con.createStatement();
        String sql="SELECT * FROM TAB";
        rs=st.executeQuery(sql); 

并尝试打印一个字段;快速测试问题是否在你准备好的声明中,但可能是在你的conn对象中。