JDBC中將圖片儲存到資料庫,jdbc中將圖片資料庫
Demo PreparedStatement setBinaryStream
表結構:
create table TEST( ID INTEGER, IMG BLOB)
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;public class Test {static {try {Class.forName("oracle.jdbc.driver.OracleDriver");} catch (ClassNotFoundException e) {e.printStackTrace();}}/** * 獲得Connection * * @return */public static Connection getConnection() {Connection conn = null;try {conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/orcl", "root", "root");} catch (SQLException e) {e.printStackTrace();}return conn;}public static void main(String[] args) {// TODO Auto-generated method stubPreparedStatement pst = null;FileInputStream fis=null;File file = new File("d:\\image.jpg");Connection conn = getConnection();String sql = "insert into test(id,img) values('1',?)";try {pst = conn.prepareStatement(sql);fis=new FileInputStream(file);pst.setBinaryStream(1, fis, fis.available());pst.executeUpdate();} catch (SQLException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}// 省略IO流close}}pst.setBinaryStream(1, fis, fis.available());
三個參數分別為:參數索引,流對象,流對象大小
作者:itmyhome
出處:http://blog.csdn.net/itmyhome1990/article/details/41824447