Unable to fetch data from MySQL database: java.lang.NullPointerException
I am trying to fetch data from a 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 error shows:
java.lang.NullPointerException
I've looked all over the place and I can't seem to find a solution. I would be grateful for any help.
+2
a source to share
2 answers
You are not initializing the array String[] subj
I 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 result set and initialize
subj = new String[resultcount]
- use an extended extension container (for example
ArrayList
) instead of a string array
+5
a source to share