我试图从MySQL数据库中读取记录,并将其放入JDBC中的类变量中,但会引发异常The Error is: java.lang. NullPointerException
。
我在这里做错了什么?
码:
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "root", "password");
st = conn.createStatement();
rs = st.executeQuery("SELECT * FROM tablename");
kids records = new kids();
int i = 0;
while (rs.next()) {
records.id[i] = rs.getInt("id");
records.name[i] = rs.getString("name");
records.user_id[i] = rs.getInt("user_id");
System.out.println("id: " + records.id[i] + "name: " + records.name[i] + "user_id" + records.user_id[i]);
i++;
}
} catch (Exception e) {
System.err.println("The Error: " + e);
}
应该存储记录的kid类如下。
public class kids{
public int id[];
public String name[];
public int user_id[];
public kids(){
for (int x=0;x<100;x++){
this.id[x]=0;
this.name[x]="";
this.user_id[x]=0;
}
}
}
最佳答案
问题在于kids
类中的数组是null
,因为这是对象的默认值(数组是对象)。您应该在类构造函数中对其进行初始化:
private static final int MAX_ARRAY = 100;
public kids(){
this.id = new int[MAX_ARRAY];
this.name = new String[MAX_ARRAY];
this.user_id= new int[MAX_ARRAY];
for (int x=0; x<MAX_ARRAY; x++){
this.id[x]=0;
this.name[x]="";
this.user_id[x]=0;
}
}
您当前的设计还有其他一些问题需要解决:
使用Java Code Conventions,因此将类
kids
重命名为Kid
,将变量kids records
重命名为Kid kid
,等等。一个类应该存储实体的数据,您的
kid
类当前正在存储数据的并行数组。最好有一个带有Kid
字段的int id; String name; int user_id;
类,而包含一个KidHolder
的Kid[] kidHolder
类。数组具有静态大小且无法更改,因此,如果您不知道将检索和保存多少个元素(例如,从数据库中检索数据时),请使用
List
。不要手动打开数据库连接,而要使用数据库连接池,因为打开数据库连接的成本很高,因此可以通过打开大量连接并使它们保持睡眠状态来增强数据库访问。
考虑到所有这些建议,您的设计应如下所示:
public class Kid {
private int id;
private String name;
private int userId;
//getters and setters
}
public class KidHolder {
private List<Kid> kidHolder;
public KidHolder() {
kidHolder = new ArrayList<Kid>();
}
public void add(Kid kid) {
}
}
//...
List<Kid> kidList = new ArrayList<Kid>();
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "root", "password");
st = conn.createStatement();
rs = st.executeQuery("SELECT * FROM tablename");
//kids records = new kids();
//int i = 0;
while (rs.next()) {
Kid kid = new Kid();
//records.id[i] = rs.getInt("id");
//records.name[i] = rs.getString("name");
//records.user_id[i] = rs.getInt("user_id");
kid.setId(rs.getInt("id"));
kid.setName(rs.getInt("name"));
kid.setUserId(rs.getInt("user_id"));
System.out.println("id: " + kid.getId() + "name: " + kid.getName() + "user_id" + kid.getUserId());
kidList.add(kid);
}
} catch (Exception e) {
System.err.println("The Error: " + e);
} finally {
closeResource(rs);
closeResource(st);
closeResource(conn);
}
//probably you should return kidList to display it in your view
//method to close the connection
//create two more similar methods to close ResultSet and Statement...
public void closeResource(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException silent) {
//...
}
}
}