Java从Oracle中插入和读取图片
下面以SWT效果来展示。
测试照片如下: 路径为: D:\test\1.png
一、插入图片
通过java的io流类读取图片资源,存储在字节数组中,直接写入到数据库类型为Blob的属性即可。
代码示例:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class test {
public static void main(String []args) throws Exception {
File file = new File("D:\\test\\1.png");
InputStream in = new FileInputStream(file);
byte [] bt = new byte[(int)file.length()];
int i = in.read(bt); //将图片存入字节数组bt中
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
int result = -1;
try( Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","a");
PreparedStatement pstmt = con.prepareStatement("insert into test_img values (?)");
){
pstmt.setObject(1, bt);
result = pstmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
if(result>=0) {
System.out.println("插入成功");
}
in.close();
}
}
Oracle查询效果:插入是成功的
二、读取图片
从数据库中读取的数据用Blob接收,然后在将他转换成字节流,再将字节流读入到字节数组中
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class test2 {
public static void main(String[]args) {
Display display = Display.getDefault();
Shell shell = new Shell();
shell.setSize(300, 300);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
byte [] bt = null;
try(Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","a");
PreparedStatement pstmt = con.prepareStatement("select * from test_img ");
){
ResultSet rs = pstmt.executeQuery();
if(rs.next()){ //只读取一行
Blob image = (Blob) rs.getObject("IMAGE"); //将从数据库中读入的数据存入Blob中
InputStream in = image.getBinaryStream() ; //将Blob转换成字节流
bt = new byte[(int)image.length()]; // 将字节流读入
int i =0 ;
while((i = in.read(bt))!=-1) {
}
}
}catch(Exception e){
e.printStackTrace();
}
Label showimage = new Label(shell, SWT.NONE);
ByteArrayInputStream in = new ByteArrayInputStream(bt); //将字节数组转换成流
Image image =new Image(Display.getDefault(),in);
showimage.setImage(image);
showimage.setBounds(0, 0, 200, 211);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
页面效果:
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。