数据库中有一张带有图像的表格。我希望在 ImageView 中显示图像,但是出现了问题并且出现了 SQLException。
ConnectionHelper ch=new ConnectionHelper();
ch.Connect();
String q="SELECT IMG FROM img_ins";
Statement st=ch.con.createStatement();
ResultSet rs = st.executeQuery(q);
InputStream is= rs.getBinaryStream("IMG");
OutputStream os=new FileOutputStream(new File("img.jpg"));
byte [] content= new byte[1024];
int size=0;
while ((size=is.read(content))!=-1){
os.write(content, 0, size);
}
os.close();
is.close();
javafx.scene.image.Image image1=new Image("file:img.jpg", image.getFitWidth(), image.getFitHeight(), true, true);
image.setImage(image1);
image.setPreserveRatio(true);
}
最佳答案
来自 ResultSet
的文档(我的重点):
A
ResultSet
object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row
因此您需要调用next()
将光标指向每一行。假设表中最多有一行,或者您只对第一行感兴趣,您可以这样做
ConnectionHelper ch=new ConnectionHelper();
ch.Connect();
String q="SELECT IMG FROM img_ins";
Statement st=ch.con.createStatement();
ResultSet rs = st.executeQuery(q);
if (rs.next()) {
InputStream is= rs.getBinaryStream("IMG");
// instead of the next 9 lines, you could just do
// javafx.scene.image.Image image1 = new Image(is);
OutputStream os=new FileOutputStream(new File("img.jpg"));
byte [] content= new byte[1024];
int size=0;
while ((size=is.read(content))!=-1){
os.write(content, 0, size);
}
os.close();
is.close();
javafx.scene.image.Image image1=new Image("file:img.jpg", image.getFitWidth(), image.getFitHeight(), true, true);
image.setImage(image1);
image.setPreserveRatio(true);
}
但也要注意OP下面的评论。
关于java - 从 DB 检索图像到 imageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43984021/