`
thomas0988
  • 浏览: 473995 次
  • 性别: Icon_minigender_1
  • 来自: 南阳
社区版块
存档分类
最新评论

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());
}
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics