我正在尝试使用BLOBS从本地数据库中保存并获取图像。尝试从本地数据库中获取一个时,在某些时候会给我Nullpointer异常。
java文件中的方法
public Image[] getCategories(){
ResultSet rs = null;
List<Image> categories = new ArrayList<>();
try {
rs = statement.executeQuery("SELECT * FROM category");
while (rs.next()) {
Blob imageBlob = rs.getBlob(3);
InputStream in = imageBlob.getBinaryStream();
BufferedImage bfImage = ImageIO.read(in);
Image image = SwingFXUtils.toFXImage(bfImage, null );
categories.add(image);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image[] itemsArray = new Image[categories.size()];
itemsArray = categories.toArray(itemsArray);
return itemsArray;
}
数据库代码
CREATE TABLE IF NOT EXISTS `order_system`.`Category` (
`idCategory` INT(11) NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(45) NOT NULL,
`Icon` LONGBLOB NULL DEFAULT NULL,
PRIMARY KEY (`idCategory`),
UNIQUE INDEX `Name_UNIQUE` (`Name` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
例外
Caused by: java.lang.NullPointerException
at javafx.swing/javafx.embed.swing.SwingFXUtils.toFXImage(SwingFXUtils.java:74)
at shop.Model.getCategories(Model.java:47)
at shop.Controller.<init>(Controller.java:21)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at java.base/java.lang.Class.newInstance(Class.java:584)
at javafx.fxml/javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:936)
at javafx.fxml/javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:980)
at javafx.fxml/javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:227)
at javafx.fxml/javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:752)
at javafx.fxml/javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2722)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2552)
... 14 more
Exception running application shop.Main