简体   繁体   中英

Can't select data from MySQL database: java.lang.NullPointerException

I'm trying to select data from database using this code:

//DATABASE
ResultSet rs;
String polecenie;
Statement st;
String[] subj;

public void polacz() {
    try {
        Class.forName("com.mysql.jdbc.Driver");

        Connection pol=DriverManager.getConnection("jdbc:mysql://localhost:3306/testgenerator", "root", "pospaz");
        st = pol.createStatement();
        lblPolaczonoZBaza.setText("Połączono z bazą danych testgenerator");

    } catch (Exception ek) {
        statusMessageLabel.setText("Can't connect to d: "+ek);
    }


    polecenie = "select * from subjects";


    try {
        rs = st.executeQuery(polecenie);
        int i=0;
        while (rs.next()){
            subj[i] = rs.getString("name");
            i++;
        }
        st.close();
    } catch (Exception ek) {
        statusMessageLabel.setText("Can't select data: "+ek);
    }
}

The second catch shows exception:

java.lang.NullPointerException

I looked everywhere and I can't find the solution. I'd be grateful for any help.

你永远不会实例化subj[] ,导致它为null

You're not initializing the String[] subj array, that I can see, so when it gets to subj[i] = ... it chokes. You need to do one of the following:

  • determine the number of rows in the resultset, and initialize subj = new String[resultcount]
  • use an auto-extending container (like an ArrayList ) instead of the string array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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