JDBC: java.lang.NullPointerException



我试图从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);
}

用于存储记录的child类如下所示。

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代码约定,将类kids重命名为Kid,将变量kids records重命名为Kid kid,然后
  • 类应该存储实体的数据,kid类当前正在存储数据的并行数组。最好是具有int id; String name; int user_id;字段的Kid类和包含Kid[] kidHolderKidHolder
  • 数组具有静态大小,不能更改,所以如果您不知道将检索和保存多少元素(例如,从数据库检索数据时),请使用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) {
//...
}
}
}

您尚未实例化任何成员,

public int id[];
public String name[];
public int user_id[];

即使是构造函数也会在this.id[x]=0;中失败

相关内容

最新更新