[英]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. 你没有初始化我可以看到的
String[] subj
数组,所以当它到达subj[i] = ...
它会窒息。 You need to do one of the following: 您需要执行以下操作之一:
subj = new String[resultcount]
subj = new String[resultcount]
ArrayList
) instead of the string array ArrayList
)而不是字符串数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.