我在这里要做的是从MySQL数据库中读取一些数据,并将它们转换为对象数据并将其序列化为一个文件。显然,它的确如此。但是我在控制台中得到一个null,我无法理解它来自哪里。如果我检查错误本身,它说,它在这条线:为什么在使用ResultSet时会得到一个额外的null结果?
pepi = (personita) ois.readObject();
你得到的输出是:
贝蒂,Laferez,87.0 < - 从数据库,OK。
Manolo,Lopez,45.0 < - 从数据库中,确定。
Manuel,Rodriguez,12.0 < - 从数据库中,确定。
Patricia,Alonso,12.0 < - 从数据库中,确定。
null < - ???
那么,你能帮我理解为什么这行代码导致null问题吗?
public class practicabdyserializableobjetos {
public static void main(String[] args) throws ClassNotFoundException, IOException {
Class.forName("com.mysql.jdbc.Driver");
Connection conexion = null;
try {
conexion = DriverManager.getConnection("jdbc:mysql://localhost/programacion", "root", "password");
Statement sentencia = (Statement) conexion.createStatement();
ResultSet resultado = sentencia.executeQuery("Select * from ejemplo");
File persofiles = new File("./persofiles.txt");
if (!persofiles.exists())
persofiles.createNewFile();
FileOutputStream fioust = new FileOutputStream(persofiles);
ObjectOutputStream oboust = new ObjectOutputStream(fioust);
int p=0;
while (resultado.next()) {
personita per = new personita();
per.setNombre(resultado.getString(1));
per.setApellido(resultado.getString(2));
per.setEdad(resultado.getDouble(3));
oboust.writeObject(per);
}
oboust.close();
fioust.close();
FileInputStream fis = new FileInputStream(persofiles);
@SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fis);
while (true) {
personita pepi = new personita();
pepi = (personita) ois.readObject();
System.out.println(pepi.getNombre() + ", " + pepi.getApellido() + ", " + pepi.getEdad());
}
} catch (SQLException e) {
e.printStackTrace();
}
catch(EOFException e){
System.out.println(e.getMessage());
}
}
}
是否像你说的那样;完全相同的错误。 –
编辑完成后,我仍然收到null。 –
你可以替换System.out.println(e.getMessage());通过e.printStackTrace();并告诉我它是否打印出不同的东西? – Juan