mysql blob (转)

MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。BLOB类型实际是个类型系列(TinyBlob、Blob、MediumBlob、LongBlob),除了在存储的最大信息量上不同外,他们是等同的。

MySQL的四种BLOB类型

 

类型大小(单位:字节)
TinyBlob最大 255
Blob最大 65K
MediumBlob最大 16M
LongBlob最大 4G

实际使用中根据需要存入的数据大小定义不同的BLOB类型。
需要注意的是:如果你存储的文件过大,数据库的性能会下降很多。

 

下面的例子是将图片存到数据库中:

package com.liuwen;

import java.io.*;
import java.sql.*;

public class PutImg {
public void putimg() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/tests?user=root&password=liuwenqiang&useUnicode=true&characterEncoding=gbk";
Connection conn = DriverManager.getConnection(url);
PreparedStatement pstmt = null;
String sql = "";
File file = new File("c:\\blog.jpg");
InputStream photoStream = new FileInputStream(file);
sql = "INSERT INTO images (Image) VALUES (?)";

pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1, photoStream, (int) file.length());

pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String args[]) {
PutImg pi = new PutImg();
pi.putimg();
}
}

这个是将数据库中的图片取出:
package com.liuwen;

import java.io.*;
import java.sql.*;

class GetImg {

private static final String URL = "jdbc:mysql://localhost/tests?user=root&password=liuwenqiang";
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
private File file = null;

public void blobRead(String outfile, int picID) throws Exception {
FileOutputStream fos = null;
InputStream is = null;
byte[] Buffer = new byte[4096];
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(URL);
pstmt = conn
.prepareStatement("select Image from images where PicNum=?");
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("Image");
int size = 0;

while ((size = is.read(Buffer)) != -1) {
fos.write(Buffer, 0, size);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
fos.close();
rs.close();
pstmt.close();
conn.close();
}
}

public static void main(String[] args) {
try {
GetImg gi = new GetImg();
gi.blobRead("c://2.jpg", 10);
} catch (Exception e) {
System.out.println("[Main func error: ]" + e.getMessage());
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值