首先是一个具体的插入操作,插入的数据包含了Blob类型,要用文件的形式等价Blob类型
1.这里有一个注意点,就是这里的girl.jpg图片文件放置的问题是很有讲究的,我是用的是idea,如果不想写什么绝对或者相对路径的话,要放在工程(Project)下。下面引用b站视频评论区的一位大兄弟的回答:
如果是用idea的话,用getResourceAsStream方法读取配置文件默认是在src下读的,而用FileInputStream读取的话分两种情况:在单元测试中,默认是在module下读的,而在main方法中,默认是在project下读的,这个要小心
比如说,如果把配置文件放在src下,用getResourceAsStream的话直接写文件名,在单元测试中用FileInputStream,需要写 src\\文件名,在main方法中用FileInputStream,需要写 module名\\src\\文件名
2.这里需要注意的是,当向数据库中存储图片的时候,图片的大小虽然没有超过数据库中规定的大小,但是仍然显示超过大小,因为以下图为例,MediumBlob类型虽然能够存储16M的图片,但是默认为1M,所以要修改配置文件,操作如下:
如果在指定了相关的Blob类型以后,还报错:xxx too large,那么在mysql的安装目录下,找my.ini文件加上如
下的配置参数: max_allowed_packet=16M。同时注意:修改了my.ini文件之后,需要重新启动mysql服务。
package com.atguigu5.blob;
import com.atguigu3.bean.Customer;
import com.atguigu3.util.JDBCUtils;
import java.io.*;
import java.sql.*;
import java.util.Date;
public class BlobTest {
public static void main(String[] args) {
//向数据表Customer中插入Blob类型的字段
Connection conn= null;
PreparedStatement ps= null;
try {
conn = JDBCUtils.getConnection();
String sql="insert into customers(name,email,birth,photo)values(?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1,"李沁");
ps.setObject(2,"zhang@qq.com");
ps.setObject(3,"1998-09-08");
FileInputStream is=new FileInputStream(new File("girl.jpg"));
ps.setBlob(4,is);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,ps);
}
}
下面是查询带有Blob类型的数据,这里读取数据库中的Blob类型的图片,直接默认输出在Project里面,这里还首次加入了输入输出流的关闭,值得借鉴!
package com.atguigu5.blob;
import com.atguigu3.bean.Customer;
import com.atguigu3.util.JDBCUtils;
import java.io.*;
import java.sql.*;
import java.util.Date;
public class BlobTest {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement ps=null;
ResultSet resultset=null;
FileOutputStream fos=null;
InputStream is=null;
try {
conn = JDBCUtils.getConnection();
String sql="select id,name,email,birth,photo from customers where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1,21);
resultset = ps.executeQuery();
if (resultset.next()){
int id=resultset.getInt("id");
String name=resultset.getString("name");
String email=resultset.getString("email");
Date birth=resultset.getDate("birth");
Customer customer=new Customer(id,name,email,birth);
System.out.println(customer);
Blob photo=resultset.getBlob("photo");
is=photo.getBinaryStream();
fos=new FileOutputStream("tupian.jpg");
byte[] buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos!=null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (is!=null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,ps,resultset);
}
}
}