java blob mysql 图片,java 向mysql插入blob的图片以及从mysql读取图片并用jsp显示

java 向mysql插入blob的图片以及从mysql读取图片并用jsp显示及CLOB2010-06-02 14:16转载自 yase_guoguo最终编辑 yase_guoguo插入图片:

注意如果mysql是gbk编码的要先把mysql的字符集设置Latin1,输入完图片后再设回来

import java.sql.*;

import java.io.*;

class InsertPhoto{

public static void main(String[] args) throws Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/tjphotodb?user=root&password=root");

File f = new File("c:/test.jpg");

FileInputStream fis = new FileInputStream(f);

String sql = "insert into tjphotodb.t_photo(alarmid,photoblob) values(0,?)";

PreparedStatement pstmt = con.prepareStatement(sql);

pstmt.setBinaryStream(1,fis,(int)f.length());

pstmt.executeUpdate();

fis.close();

pstmt.close();

con.close();

}

}

读取并显示图片:

后台用一个servlet来读取,然后让前台的jsp显示

后台servlet:

public static InputStream query_getPhotoImageBlob(int id){

String sql = "select photoblob from "+DB_TABLE_PHOTO+" where id="+id;

Connection con = null;

Statement stmt = null;

ResultSet rs = null;

InputStream result = null;

try {

con = getConnection();

stmt = con.createStatement();

rs = stmt.executeQuery(sql);

if (rs.next())

result = rs.getBlob("photoblob").getBinaryStream();

} catch (SQLException e) {

// TODO: handle exception

System.err.println(e.getMessage());

}finally{

closeConnection(rs,stmt,con);

}

return result;

}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

if (request.getParameter("id") != null){

response.setContentType("image/jpeg");

InputStream is = DBUtil.query_getPhotoImageBlob(Integer.valueOf(request.getParameter("id")).intValue());

if (is != null){

try {

is = new BufferedInputStream(is);

BufferedImage bi = ImageIO.read(is);

OutputStream os = response.getOutputStream();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);

encoder.encode(bi);

os.close();

is.close();

} catch (IOException e) {

// TODO: handle exception

System.err.println(e.getMessage());

}

}

}

}

前台jsp:

genImage?id=<%=request.getParameter("/>

import java.io.*;

import java.sql.*;

public class DBTest {

public static void main(String[] args) {

String driver = "com.mysql.jdbc.Driver";

String url = "jdbc:mysql://localhost:3306/upload?useUnicode=true&characterEncoding=Big5";

String user = "caterpillar";

String password = "123456";

try {

Class.forName(driver);

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值