java连接到Oracle DB java.lang.NullPointerException

时间:2015-05-24 18:33:22

标签: java oracle swing

我遇到了以下代码问题。

当我尝试连接并从数据库中获取数据时,我得到NullPointerException。我认为在执行executeQuery时会收到错误。据我所知,代码是正确的,但是作为sys连接到数据库的方式仍然是我不确定的。

这里是:

package masterdocument;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
import java.lang.*;
import oracle.jdbc.driver.*;
public class JavaConnectDB {
public static Connection ConnecrDB(){
try{
    String driverName = "oracle.jdbc.driver.OracleDriver";
    Class.forName(driverName).newInstance();
    String nameForConnect = "sys as sysdba";
    String pass = "Abcd1234";
    String url = "jdbc:oracle:thin:@localhost:1521:db01";
    Connection conn = DriverManager.getConnection(url, nameForConnect, pass);
    System.out.println(conn);
    return conn;
    }
catch (Exception e){
    JOptionPane.showMessageDialog(null,e);
    return null;
    }    
 }
}

以及对上述连接的调用:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)         {                                         

conn = JavaConnectDB.ConnecrDB();
        try{
            String sql="select * from TUTILIZADORES where USERNAME=? and PASSWORD=?";
        pst.setString(1, USERNAME.getText());
        pst.setString(2, PASSWORD.getText());
        rs=(OracleResultSet)pst.executeQuery();
        if (rs.next()){
        JOptionPane.showMessageDialog(null, "O username e password estavam bem");

        Tutilizadores c = new Tutilizadores();
        c.setVisible(true);
        }
        else{
        JOptionPane.showMessageDialog(null, "Login Inválido");
        }

    } catch(Exception e){
                        JOptionPane.showMessageDialog(null,e);
                        }       
}      

我对Java有点新鲜。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可能错过了创建PreparedStatement的部分:

String sql="select * from TUTILIZADORES where USERNAME=? and PASSWORD=?";
pst = conn.prepareStatement(sql);

在完成使用后,您还应确保关闭此声明和ResultSet。您可以在finally块中执行此操作:

} catch(Exception e) {
     JOptionPane.showMessageDialog(null ,e);
} finally {
   if(rs != null) {
       rs.close();
   }
   if(pst != null) {
       pst.close();
   }
}