blob类型字段
1、在mysql中,bolb是一个二进制大型对象,是一个储存大量数据的容器,例如图片,音频。2、插入blob类型数据比如使用preparedStatement,而不能使用Statment,因为blob类型数据不能使用字符串拼接。有关preparedStatement的使用请参考https://blog.csdn.net/weixin_46457946/article/details/1197812
·
1、在mysql中,bolb是一个二进制大型对象,是一个储存大量数据的容器,例如图片,音频。
2、插入blob类型数据比如使用preparedStatement,而不能使用Statment,因为blob类型数据不能使用字符串拼接。有关preparedStatement的使用请参考https://blog.csdn.net/weixin_46457946/article/details/119781227
3、mysql的四种blob类型
类型 | 大小 |
---|---|
TinyBlob | 255byte |
Blob | 65k |
MediumBlob | 16M |
Long | 4G |
4、储存的文件过大,会造成数据库的性能下降。
一、Blob数据类型应用,向数据库中插入图片
@Test
public void testInsert() {
Connection conn=null;
PreparedStatement ps=null;
try {
//1、连接数据库
conn = JDBCUtils.getConnection();
//2、预编译sql
String sql = "insert into customers(name,email,birth,photo) values(?,?,?,?)";
//3、获得PreparedStatement对象
ps = conn.prepareStatement(sql);
ps.setObject(1, "刘备");
ps.setObject(2, "liu@qq.com");
ps.setObject(3, "1992-09-08");
FileInputStream is = new FileInputStream(new File("推广004.png"));
ps.setBlob(4, is);
//提交
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResouce(conn, ps);
}
}
二、从数据库中读取Blob数据
@Test
public void testQuery(){
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
InputStream is=null;
FileOutputStream fos=null;
try {
//1、连接数据库
conn = JDBCUtils.getConnection();
//2、预编译sql
String sql = "select id,name,email,birth,photo from customers where id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, 27);
//3、提交数据
rs = ps.executeQuery();
if(rs.next()){
int id=rs.getInt("id");
String name=rs.getString("name");
String email=rs.getString("email");
Date birth = rs.getDate("birth");
Customer cus = new Customer(id,name,email,birth);
System.out.println(cus);
//将Blob类型以文件的方式保存在本地
Blob photo = rs.getBlob("photo");
is = photo.getBinaryStream();
fos = new FileOutputStream("01.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,ps,rs);
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)