日期:2014-05-16  浏览次数:20466 次

ORACLE如何使用BLOB,LONG RAW类型存储图片
以下代码可以向数据库插入二进制形式的图片、文件、视频等。
Java代码
package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class OracleImageTest {
	/*
	 * create table IMAGETABLE ( IMAGE_BLOB BLOB, IMAGE_LONG_RAW LONG RAW )
	 */

	public static void main(String[] args) {
		Connection connection = null;
		try {
			String sql = "insert into imagetable (image_blob )values (?  )";
			connection = getORACLEConn();

			File f = new File("c://myimage.png");
			FileInputStream fis = new FileInputStream(f);

			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setBinaryStream(1, fis, f.length());
			ps.execute();

			fis = new FileInputStream(f);
			sql = "insert into imagetable (image_long_raw )values (? )";
			ps = connection.prepareStatement(sql);
			ps.setBinaryStream(1, fis, f.length());
			ps.execute();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static Connection getORACLEConn() throws ClassNotFoundException,
			SQLException {
		Connection connection;
		Class.forName("oracle.jdbc.driver.OracleDriver");
		connection = DriverManager.getConnection(
				"jdbc:oracle:thin:@192.168.65.247:1521:ce4702", "qsh91",
				"qsh91");
		return connection;
	}
}
?通过PL/SQL就可以看到插入的图片,或者通过相反的JDBC过程就可以查询出图片。