将图片保存到数据库中
原理:将图片转换成二进制流,然后将二进制流保存到数据库中。
要求存储图片的字段的数据类型为二进制类型。
MySQL中共有4种二进制的数据类型(除了存储的最大信息量不同外,没有区别)
- blob 存储上限是65KB
- tinyblob 存储上限是255KB
- mediumblob 存储上限是16MB
- longblob 存储上限是4GB
- 在数据表中添加blob类型的字段
- 通过Java程序完成图片的保存:使用InputStream将图片以流的形式读取到Java程序中,再通过JDBC将二进制数据存入数据库。
public class ReadImg {
public static void main(String[] args) {
Connection connection = JDBCTools.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String sql = "select * from t_user where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,30);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
int id = resultSet.getInt(1);
String username = resultSet.getString(2);
String password = resultSet.getString(3);
int age = resultSet.getInt(4);
Blob file = resultSet.getBlob(5);
System.out.println(id);
System.out.println(username);
System.out.println(password);
System.out.println(age);
System.out.println(file);
inputStream = file.getBinaryStream();
outputStream = new FileOutputStream("2.png");
int temp = 0;
while((temp = inputStream.read())!=-1){
outputStream.write(temp);
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally {
JDBCTools.release(connection,preparedStatement,resultSet);
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class WriteImg {
public static void main(String[] args) {
Connection connection = JDBCTools.getConnection();
PreparedStatement preparedStatement = null;
try {
InputStream inputStream = new FileInputStream("1.png");
System.out.println(inputStream.available());
String sql = "insert into t_user(username,password,age,file) values(?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"图片");
preparedStatement.setString(2,"000");
preparedStatement.setInt(3,18);
preparedStatement.setBlob(4,inputStream);
preparedStatement.executeUpdate();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
}finally {
JDBCTools.release(connection,preparedStatement,null);
}
}
}