运行executeQuery()时可以抛出什么可能的异常

时间:2010-11-24 23:22:12

标签: java

我正在运行JConnector来从数据库中获取数据(我使用的是mysql)。我检查了从Secure Shell运行查询的数据,它运行正常。但是,当我运行程序时它抛出NullPointerException,它只读取第一行。我刚学了一个月的Java,很抱歉,如果我的问题听起来很奇怪你们。 这是我的代码:

    private void loadNodesFromDatabase()
    {
        Statement stmt = Database.connect();
        String query = "SELECT * FROM Node";
        ResultSet res;
        try 
        {
            res = stmt.executeQuery( query );
            while( res.next() ) 
            {
                Integer id = res.getInt( "Id" );
                String position = res.getString( "Position" );
                String rule = res.getString(  "RuleOnMap" );
                Integer foodTax = res.getInt(  "FoodTax" );
                boolean mapValue = res.getBoolean( "MapValue" );

                Node n = new Node( id, PointOnGraph.parse( position ), Node.RuleOnMap.valueOf( rule ), foodTax, mapValue );
                System.out.println( n );
                nodes.add( n );
            }
            res.close();
         }
         catch( Exception e ) 
         { 
             System.out.println( "Selection Error:  " + e );  
         }  
    } 

这是我创建表格的查询:

mysql> CREATE TABLE Node (Id INT(3), Position VARCHAR(12),  RuleOnMap VARCHAR(6), FoodTax INT(2), MapValue TINYINT(1), PRIMARY KEY(Id));

这是来自Eclipse的错误消息:

( 1, '20,20,88', PAY, 10, false )
Selection Error:  java.lang.NullPointerException
...

谢谢,

调用e.printStackTrace();

之后
 ( 1, '20,20,88', PAY, 10, true )
Selection Error: java.lang.NullPointerException
java.lang.NullPointerException
    at Game.Game.loadNodesFromDatabase(Game.java:177)
    at Game.Game.<init>(Game.java:31)
    at Test.GameLoadDatabseTest.loadNodesTest(GameLoadDatabseTest.java:30)
    at Program.main(Program.java:39)
Exception in thread "main" java.lang.NullPointerException
    at Test.GameLoadDatabseTest.loadNodesTest(GameLoadDatabseTest.java:32)
    at Program.main(Program.java:39)

祝你好运, Chan Nguyen

1 个答案:

答案 0 :(得分:2)

看起来第一个n打印出来,对吧?

在这种情况下,我的赌注是nodesnull。你忘了初始化List吗?