Mysql 为什么在使用ResultSet时会得到一个带有null的额外结果?
我在这里试图做的是从MySQL数据库中读取一些数据,然后将它们转换为对象数据并在文件中序列化。显然是这样。但我在控制台中得到一个空值,我无法理解它来自哪里。如果我检查错误本身,它会在这行上显示:Mysql 为什么在使用ResultSet时会得到一个带有null的额外结果?,mysql,resultset,Mysql,Resultset,我在这里试图做的是从MySQL数据库中读取一些数据,然后将它们转换为对象数据并在文件中序列化。显然是这样。但我在控制台中得到一个空值,我无法理解它来自哪里。如果我检查错误本身,它会在这行上显示: pepi = (personita) ois.readObject(); 您得到的输出是: Betty,Laferez,87.0编辑2-我更改了我的答案 看完这个 你的代码是正确的。 您得到的空值是EOFEException捕获中的e.getMessage(),您只需将System.println语句
pepi = (personita) ois.readObject();
您得到的输出是:
Betty,Laferez,87.0编辑2-我更改了我的答案 看完这个 你的代码是正确的。 您得到的空值是EOFEException捕获中的e.getMessage(),您只需将System.println语句替换为“;”)即可避免该错误
与我认为的相反,您在steram的endo处没有读取空值,因此为了知道何时到达流的末尾,您使用这个EOFEException。在我提到的问题中,有一个需要考虑的问题,因为您需要知道EOF raise是否是因为没有更多的对象可读取,或者是因为有错误且流已关闭。您是否可以替换System.out.println(e.getMessage());由e.printStackTrace()编写;并告诉我它是否打印了一些不同的内容?与我的原始代码:java.io.ObjectInputStream中的java.io.EOFEException$BlockDataInputStream.peekByte(未知源)位于java.io.ObjectInputStream.readObject0(未知源)位于java.io.ObjectInputStream.readObject(未知源)在Tema8.practicabdmasobeTosserializasdos.practicabdyserializableobjetos.main(practicabdyserizableObjetos.java:53)(第53行与我在上面突出显示的相同)编辑2:所以,我认为这是因为没有更多的对象可读取。然后,它似乎不是一个错误的代码,但我需要它来让它工作。谢谢你的帮助!
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());
}
}
}catch(EOFException e){
;
}