java.lang.NullPointerException ...初始化JDBC MYSQL连接

时间:2014-01-27 18:47:09

标签: java mysql swing

请不要建议我使用InternalFrame或Dialogs。我从一开始就无法启动项目。 主题:我正在构建一个GUI程序来显示标记表。我拍了3张JFrames& 1个简单的课程......

  

Frame1.java

它有1个JTextField来输入roll_no。 &安培;在DB&amp ;;中输入数据的2个按钮showResult。 feedData按钮调用Frame2& showResult按钮调用Frame3。

  

Frame2.java

对于喂食数据有几个JTextFields&将内容传输到mySQL DB的按钮。

  

Frame3.java

是一个从DB获取内容的结果窗口。

  

Support.java

包含静态变量&他们的getter-setter方法

 .....
 .....//contains in Support.java
     public boolean add() {
    query = "Insert into table1 (enroll,Sname,Fname,sub1,sub2,sub3,sub4,sub5 )values(?,?,?,?,?)";
    try {
        PreparedStatement psmt = conn.prepareStatement(query);
        psmt.setString(1, enroll);
        psmt.setString(2, Sname);
        psmt.setString(3, Fname);
        psmt.setInt(4, sub1);
        psmt.setInt(5, sub2);
        psmt.setInt(6, sub3);
        psmt.setInt(7, sub4);
        psmt.setInt(8, sub5);
        int y = 0;
        y = psmt.executeUpdate();
        if (y == 0) {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

在Frame2.java中按下保存按钮时调用add()。 。 。如果catch块正在执行,为什么println(查询)打印NULL

3 个答案:

答案 0 :(得分:5)

根据您对其他答案和问题本身的评论中的一些问题标签和回复,我假设您的代码中的某个地方,您打算致电

Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);

在调用add()方法之前不会发生这种情况。为了解决这个问题,我建议这个(从Vivek bhatnagar的答案借来的大量代码):

try {
    conn = DriverManager.getConnection(url, username, password);
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `table`
        (pid,tid,rid,tspend,description) VALUE 
        (?,?,?,?,?)");
    pstmt.setString(1, pid );
    pstmt.setString(2, tid);
    pstmt.setString(3, rid);
    pstmt.setInt(4, tspent);
    pstmt.setString(5,des );
    pstmt.executeUpdate();
} catch (Exception e) {
    // whatever you want to do to handle the exception
} finally {
    // close your connection
}

如果你使用的是Java 7,请设置如下:

try (Connection conn = DriverManager.getConnection(url, username, password)) {
    try (PreparedStatement pstmt = conn.prepareStatement(/*sql here*/)) {
        // Your code here
    } catch (SQLException sqle) {
        // handle exceptions from the statement
    }
} catch (SQLException outerSqlEx) {
    // handle exceptions from connecting
}

我怎么知道你的问题是什么(NullPointerException的一般帮助)?

当您尝试在NullPointerException变量上调用方法时(以及在其他几个特定时间,如API文档中所述),只会抛出

null。找到NullPointerException的简单方法是查找堆栈跟踪指示的行,然后查找该行上的点。 try块中只有两行可以抛出NullPointerException

Statement stmt = conn.createStatement();
// could be here ----^ 

y = stmt.executeUpdate(query);
// or --^

让我们看一下这些点。当connnull时,第一个将抛出。当stmtnull时,第二个将抛出。在您现在编辑以响应其他答案的原始代码中,在调用query后设置conn.createStatement();的值。由于query块中catch仍然为空,我们知道它尚未设置,因此它必须是第一个,因此connnull在该计划的那一点。

此外,由于API Documentation for createStatement 意味着它将返回有效的Connection对象或抛出SQLException,我们可以肯定stmt在调用null时永远不会executeUpdate

答案 1 :(得分:0)

在你的try块中,你在设置有问题的变量之前调用一个可能抛出异常的方法

    Statement stmt = conn.createStatement();
    query = "Insert into table1 (enroll,Sname,Fname,sub1,sub2,sub3,sub4,sub5 )values('" + getEnroll() + "','" + getSname() + "','"+getFname()+"',"+getSub1()+","+getSub2()+","+getSub3()+","+getSub4()+","+getSub5()+")";

因此,如果您的代码在conn.createStatement()行上失败,它将进入catch块而不初始化查询变量。

您可以通过切换语句的顺序或将查询行放在try / catch块之外和之前来解决此问题。

答案 2 :(得分:-1)

添加@Southpaw的答案:

你也可以使用这样的东西:

PreparedStatement pstmt = con.prepareStatement("INSERT INTO `table`
        (pid,tid,rid,tspend,description) VALUE 
        (?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();

请注意其好处:

1."Query is rewritten and compiled by the database server"

If you don't use a prepared statement, the database server will have to parse, and compute an execution plan for the statement each time you run it. If you find that you'll run the same statement multiple times (with different parameters) then its worth preparing the statement once and reusing that prepared statement. If you are querying the database adhoc then there is probably little benefit to this.

2."Protected against SQL injection"

This is an advantage you almost always want hence a good reason to use a PreparedStatement everytime. Its a consequence of having to parameterize the query but it does make running it a lot safer. The only time I can think of that this would not be useful is if you were allowing adhoc database queries; You might simply use the Statement object if you were prototyping the application and its quicker for you, or if the query contains no parameters.