使用java语言 *** 作,如何来实现MySQL中Blob字段的存取

使用java语言 *** 作,如何来实现MySQL中Blob字段的存取,第1张

/**

* Title: BlobPros.java

* Project: test

* Description: 把图片存入mysql中的blob字段,并取出

* Call Module: mtools数据库中的tmp表

* File: C:downloadsluozsh.jpg

* Copyright: Copyright (c) 2003-2003

* Company: uniware

* Create Date: 2002.12.5

* @Author: ChenQH

* @version 1.0 版本*

*

* Revision history

* Name Date Description

* ---- ---- -----------

* Chenqh 2003.12.5 对图片进行存取

*

* note: 要把数据库中的Blob字段设为longblob

*

*/

//package com.uniware

import java.io.*

import java.util.*

import java.sql.*

public class BlobPros

{

private static final String URL = "jdbc:mysql://10.144.123.63:3306/mtools?user=wind&password=123&useUnicode=true"

private Connection conn = null

private PreparedStatement pstmt = null

private ResultSet rs = null

private File file = null

public BlobPros()

{

}

/**

* 向数据库中插入一个新的BLOB对象(图片)

* @param infile 要输入的数据文件

* @throws java.lang.Exception

*/

public void blobInsert(String infile) throws Exception

{

FileInputStream fis = null

try

{

Class.forName("org.gjt.mm.mysql.Driver").newInstance()

conn = DriverManager.getConnection(URL)

file = new File(infile)

fis = new FileInputStream(file)

//InputStream fis = new FileInputStream(infile)

pstmt = conn.prepareStatement("insert into tmp(descs,pic) values(?,?)")

pstmt.setString(1,file.getName())//把传过来的第一个参数设为文件名

//pstmt.setBinaryStream(2,fis,(int)file.length())//这种方法原理上会丢数据,因为file.length()返回的是long型

pstmt.setBinaryStream(2,fis,fis.available())//第二个参数为文件的内容

pstmt.executeUpdate()

}

catch(Exception ex)

{

System.out.println("[blobInsert error : ]" + ex.toString())

}

finally

{

//关闭所打开的对像//

pstmt.close()

fis.close()

conn.close()

}

}

/**

* 从数据库中读出BLOB对象

* @param outfile 输出的数据文件

* @param picID 要取的图片在数据库中的ID

* @throws java.lang.Exception

*/

public void blobRead(String outfile,int picID) throws Exception

{

FileOutputStream fos = null

InputStream is = null

byte[] Buffer = new byte[4096]

try

{

Class.forName("org.gjt.mm.mysql.Driver").newInstance()

conn = DriverManager.getConnection(URL)

pstmt = conn.prepareStatement("select pic from tmp where id=?")

pstmt.setInt(1,picID)//传入要取的图片的ID

rs = pstmt.executeQuery()

rs.next()

file = new File(outfile)

if(!file.exists())

{

file.createNewFile()//如果文件不存在,则创建

}

fos = new FileOutputStream(file)

is = rs.getBinaryStream("pic")

int size = 0

/* while(size != -1)

{

size = is.read(Buffer)//从数据库中一段一段的读出数据

//System.out.println(size)

if(size != -1) //-1表示读到了文件末

fos.write(Buffer,0,size)

} */

while((size = is.read(Buffer)) != -1)

{

//System.out.println(size)

fos.write(Buffer,0,size)

}

}

catch(Exception e)

{

System.out.println("[OutPutFile error : ]" + e.getMessage())

}

finally

{

//关闭用到的资源

fos.close()

rs.close()

pstmt.close()

conn.close()

}

}

public static void main(String[] args)

{

try

{

BlobPros blob = new BlobPros()

//blob.blobInsert("C:Downloadsluozsh1.jpg")

blob.blobRead("c:/downloads/1.jpg",47)

}

catch(Exception e)

{

System.out.println("[Main func error: ]" + e.getMessage())

}

}

}

在OracleQueryBean类中增加一个函数,来进行读取,具体代码如下:

/**

* 根据图片在数据库中的ID进行读取

* @param strID 图片字段ID

* @param w 需要缩到的宽度

* @param h 需要缩到高度

* @return

*/

public byte[] GetImgByteById(String strID, int w, int h){

//System.out.println("Get img data which id is " + nID)

if(myConnection == null)

this.getConnection()

byte[] data = null

try {

Statement stmt = myConnection.createStatement()

ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID)

StringBuffer myStringBuffer = new StringBuffer()

if (myResultSet.next()) {

java.sql.Blob blob = myResultSet.getBlob(this.strImgName)

InputStream inStream = blob.getBinaryStream()

try {

long nLen = blob.length()

int nSize = (int) nLen

//System.out.println("img data size is :" + nSize)

data = new byte[nSize]

inStream.read(data)

inStream.close()

} catch (IOException e) {

System.out.println("获取图片数据失败,原因:" + e.getMessage())

}

data = ChangeImgSize(data, w, h)

}

System.out.println(myStringBuffer.toString())

myConnection.commit()

myConnection.close()

} catch (SQLException ex) {

System.out.println(ex.getMessage())

}

return data

}

页面使用OracleQueryBean来根据用户提供的图片id进行查询,在读取并进行缩放后,通过jsp页面进行展示,具体代码如下:

<%@ page language="java" contentType="text/htmlcharset=gbk" %>

<jsp:useBean id="OrcleQuery" scope="page" class="HLFtiDemo.OracleQueryBean" />

<%

response.setContentType("image/jpeg")

//图片在数据库中的 ID

String strID = request.getParameter("id")

//要缩略或放大图片的宽度

String strWidth = request.getParameter("w")

//要缩略或放大图片的高度

String strHeight = request.getParameter("h")

byte[] data = null

if(strID != null){

int nWith = Integer.parseInt(strWidth)

int nHeight = Integer.parseInt(strHeight)

//获取图片的byte数据

data = OrcleQuery.GetImgByteById(strID, nWith, nHeight)

ServletOutputStream op = response.getOutputStream()

op.write(data, 0, data.length)

op.close()

op = null

response.flushBuffer()

//清除输出流,防止释放时被捕获异常

out.clear()

out = pageContext.pushBody()

}

%>

整个流程分为四步,连接oracle数据库 ->读取blob图片字段 ->对图片进行缩放 ->把图片展示在jsp页面上。

下面进行详细描述:

1. java连接Oracle

注:数据库是Oracle10g版本为10.2.0, 在数据库中,图片字段类型为BLOB。

java中通常使用的是通过jdbc驱动来连接数据库,oracle也不例外,因此必须下载一个Oracle驱动的jdbc需要去网上进行下载,名称为 ojdbc14.jar。

下载地址为:

下载了驱动之后,可以使用驱动里提供的接口进行连接,具体代码如下:

import java.sql.*

import java.io.*

import javax.imageio.ImageIO

import java.awt.image.BufferedImage

import java.awt.image.AffineTransformOp

import java.awt.geom.AffineTransform

public class OracleQueryBean {

private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver"

private Connection myConnection = null

/*图片表名*/

private String strTabName

/*图片ID字段名*/

private String strIDName

/*图片字段名*/

private String strImgName

/**

* 加载java连接Oracle的jdbc驱动

*/

public OracleQueryBean(){

try{

Class.forName(oracleDriverName)

}catch(ClassNotFoundException ex){

System.out.println("加载jdbc驱动失败,原因:" + ex.getMessage())

}

}

/**

* 获取Oracle连接对象

* @return Connection

*/

public Connection getConnection(){

try{

//用户名+密码以下使用的Test就是Oracle里的表空间

//从配置文件中读取数据库信息

GetPara oGetPara = new GetPara()

String strIP = oGetPara.getPara("serverip")

String strPort = oGetPara.getPara("port")

String strDBName = oGetPara.getPara("dbname")

String strUser = oGetPara.getPara("user")

String strPassword = oGetPara.getPara("password")

this.strTabName = oGetPara.getPara("tablename")

this.strIDName = oGetPara.getPara("imgidname")

this.strImgName = oGetPara.getPara("imgname")

String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName

this.myConnection = DriverManager.getConnection(oracleUrlToConnect, strUser, strPassword)

}catch(Exception ex){

System.out.println("Can not get connection:" + ex.getMessage())

System.out.println("请检测配置文件中的数据库信息是否正确." )

}

return this.myConnection

}

}

2. 读取blob字段

在OracleQueryBean类中增加一个函数,来进行读取,具体代码如下:

/**

* 根据图片在数据库中的ID进行读取

* @param strID图片字段ID

* @param w 需要缩到的宽度

* @param h 需要缩到高度

* @return

*/

public byte[] GetImgByteById(String strID, int w, int h){

//System.out.println("Get img data which id is " + nID)

if(myConnection == null)

this.getConnection()

byte[] data = null

try {

Statement stmt = myConnection.createStatement()

ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID)

StringBuffer myStringBuffer = new StringBuffer()

if (myResultSet.next()) {

java.sql.Blob blob = myResultSet.getBlob(this.strImgName)

InputStream inStream = blob.getBinaryStream()

try {

long nLen = blob.length()

int nSize = (int) nLen

//System.out.println("img data size is :" + nSize)

data = new byte[nSize]

inStream.read(data)

inStream.close()

} catch (IOException e) {

System.out.println("获取图片数据失败,原因:" + e.getMessage())

}

data = ChangeImgSize(data, w, h)

}

System.out.println(myStringBuffer.toString())

myConnection.commit()

myConnection.close()

} catch (SQLException ex) {

System.out.println(ex.getMessage())

}

return data

}

3. 缩放图片

因为图片的大小可能不一致,但是在页面中输出的大小需要统一,所以需要

在OracleQueryBean类中增加一个函数,来进行缩放,具体代码如下:

/**

* 缩小或放大图片

* @param data 图片的byte数据

* @param w 需要缩到的宽度

* @param h 需要缩到高度

* @return 缩放后的图片的byte数据

*/

private byte[] ChangeImgSize(byte[] data, int nw, int nh){

byte[] newdata = null

try{

BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data))

int w = bis.getWidth()

int h = bis.getHeight()

double sx = (double) nw / w

double sy = (double) nh / h

AffineTransform transform = new AffineTransform()

transform.setToScale(sx, sy)

AffineTransformOp ato = new AffineTransformOp(transform, null)

//原始颜色

BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR)

ato.filter(bis, bid)

//转换成byte字节

ByteArrayOutputStream baos = new ByteArrayOutputStream()

ImageIO.write(bid, "jpeg", baos)

newdata = baos.toByteArray()

}catch(IOException e){

e.printStackTrace()

}

return newdata

}

4. 展示在页面

页面使用OracleQueryBean来根据用户提供的图片id进行查询,在读取并进行缩放后,通过jsp页面进行展示,具体代码如下:

<%@ page language="java" contentType="text/htmlcharset=gbk" %>

<jsp:useBean id="OrcleQuery" scope="page" class="HLFtiDemo.OracleQueryBean" />

<%

response.setContentType("image/jpeg")

//图片在数据库中的 ID

String strID = request.getParameter("id")

//要缩略或放大图片的宽度

String strWidth = request.getParameter("w")

//要缩略或放大图片的高度

String strHeight = request.getParameter("h")

byte[] data = null

if(strID != null){

int nWith = Integer.parseInt(strWidth)

int nHeight = Integer.parseInt(strHeight)

//获取图片的byte数据

data = OrcleQuery.GetImgByteById(strID, nWith, nHeight)

ServletOutputStream op = response.getOutputStream()

op.write(data, 0, data.length)

op.close()

op = null

response.flushBuffer()

//清除输出流,防止释放时被捕获异常

out.clear()

out = pageContext.pushBody()

}

%>

5. OracleQueryBean查询类的整体代码

OracleQueryBean.java文件代码如下所示:

import java.sql.*

import java.io.*

import javax.imageio.ImageIO

import java.awt.image.BufferedImage

import java.awt.image.AffineTransformOp

import java.awt.geom.AffineTransform

public class OracleQueryBean {

private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver"

private Connection myConnection = null

/*图片表名*/

private String strTabName

/*图片ID字段名*/

private String strIDName

/*图片字段名*/

private String strImgName

/**

* 加载java连接Oracle的jdbc驱动

*/

public OracleQueryBean(){

try{

Class.forName(oracleDriverName)

}catch(ClassNotFoundException ex){

System.out.println("加载jdbc驱动失败,原因:" + ex.getMessage())

}

}

/**

* 获取Oracle连接对象

* @return Connection

*/

public Connection getConnection(){

try{

//用户名+密码以下使用的Test就是Oracle里的表空间

//从配置文件中读取数据库信息

GetPara oGetPara = new GetPara()

这文章确实写的不错,你可以看原文


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/6733583.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-27
下一篇2023-03-27

发表评论

登录后才能评论

评论列表(0条)

    保存