Nullpointer异常(Derby,JDBC)

时间:2011-03-14 20:27:59

标签: java exception jdbc nullpointerexception derby

HY !!

我的错误代码:

Exception in thread "main" java.lang.NullPointerException
        at lesebank.Konto.getKontofromID(Konto.java:39)
        at lesebank.Main.main(Main.java:18)
SQL EXCEPTIONJava Result: 1
BUILD SUCCESSFUL (total time: 1 second)

方法:

Konto konto = new Konto ();
        Statement s = dbconn.getSt();
        try
        { //in the next line the error occurs
           s.execute("select id,inhaberin,ktostd,habenzinsen,notiz from Konto where id = " +id);
           ResultSet set = s.getResultSet();
           if (set.next())
           {
               konto.setId(set.getInt(1));
               konto.setId_inhaberin(set.getInt(2));
               konto.setKtostd(set.getDouble(3));
               konto.setHabenzinsen(set.getDouble(4));
               konto.setNotiz(set.getString(5));
               return konto;
           }
        }
        catch (SQLException ex)
        {
            System.out.print(ex.getMessage());
        }


        return null;

DBConn:

public class DBConnection {

   private String url = "jdbc:derby://localhost:1527/Bank";
   private Connection conn;
   private Statement st;

    public DBConnection() {
        try
        {
            conn = DriverManager.getConnection(this.url, "test", "test");
            st = conn.createStatement();

        }
        catch (SQLException ex)
        {
           System.out.print("SQL EXCEPTION");
        }
    }

    public Statement getSt() {
        return st;
    }

数据库: Database

请帮忙

3 个答案:

答案 0 :(得分:2)

这是非常糟糕的(tm):

public DBConnection() {
    try
    {
        conn = DriverManager.getConnection(this.url, "test", "test");
        st = conn.createStatement();

    }
    catch (SQLException ex)
    {
       System.out.print("SQL EXCEPTION");
    }
}

捕获并忽略此类异常。有一个非常的充分理由。在这种情况下,如果构造函数由于异常而失败,则整个DbConnection对象将变为无效,因为st字段将为null。然而,因为实例化DbConnection的代码不知道发生了这种情况,所以继续使用它,最后得到空指针异常。

如果DbConnection的构造函数触发异常,则需要从构造函数中抛出该异常,强制您的代码处理异常:

public class DBConnection {

   private static final String URL = "jdbc:derby://localhost:1527/Bank";
   private final  Connection conn;
   private final Statement st;

    public DBConnection() throws SQLException {
        conn = DriverManager.getConnection(URL, "test", "test");
        st = conn.createStatement();
    }

    public Statement getSt() {
        return st;
    }
}

还请注意final字段。这为您提供了编译时保证,某些将被分配给这些字段。

答案 1 :(得分:0)

请检查dbconn.getSt()是否未归还null无论如何,getSt()是什么;像createStatement()这样的东西?现在我看到你的编辑了,你的DBConn类很可能在调用createStatement()时没有成功。

答案 2 :(得分:0)

现在还不能测试,但是我想你会让你的DBConnection.getSt()方法返回一个全新的Statement对象,而不是一遍又一遍地重复使用同一个对象。会是这样的:

public Statement getSt() {
    return conn.createStatement();
}

请务必在使用后关闭您的声明。