简体   繁体   English

使用JDBC查询执行executeUpdate时出现空指针异常

[英]Null Pointer Exception while executeUpdate for a query using JDBC

I am getting a Null Pointer Exception while executing the insert query. 执行插入查询时,我得到了空指针异常。 Everything seems to be fine but the problem still exists. 一切似乎都很好,但问题仍然存在。

Code used for Database Connection. 用于数据库连接的代码。

public class DBConnect 
{
    static Connection c ;
    static Statement st ;
    {
        try 
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","ashuthesmartest","ashutosha");
            st=c.createStatement();
        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(null, "Database error");
        }
    }   
}

Action Performed on Button Click 单击按钮时执行的操作

private void b3ActionPerformed(java.awt.event.ActionEvent evt) {                                   
    try 
    {
        char[] arr = pa1.getPassword() ;
        String s2 = Arrays.toString(arr) ;
        String s1 = t3.getText() ;
        DBConnect.st.executeUpdate("insert into LOGIN values('"+s1+"','"+s2+"')");   **//EXCEPTION IN THIS LINE**
    } 
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }
} 

The initialization block in which you create the connection and the statement is not a static initialization block. 在其中创建连接和该语句的初始化块不是静态初始化块。

Therefore, it will only be executed when you create an instance of the class DBConnect . 因此,只有在创建类DBConnect的实例时才执行它。

Since you seem to be using DBConnect only statically, that never happens. 由于您似乎只是静态地使用DBConnect ,所以永远不会发生。 Your initialization block should be made static. 您的初始化块应设为静态。 A static initialization block has the keyword static preceding the left brace: 静态初始化块的左括号前面有关键字static

static {
    // try etc.
}

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

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