微信登录

JDBC - PS - 增删改 - 图片blob

两个例子

从电脑端存图片到数据库
从数据库查图片

  1. package com.atguigu5.blob;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.sql.Blob;
  9. import java.sql.Connection;
  10. import java.sql.Date;
  11. import java.sql.PreparedStatement;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import org.junit.Test;
  15. import com.atguigu3.bean.Customer;
  16. import com.atguigu3.util.JDBCUtils;
  17. /**
  18. *
  19. * @Description 测试使用PreparedStatement操作Blob类型的数据
  20. * @author shkstart Email:shkstart@126.com
  21. * @version
  22. * @date 下午4:08:58
  23. *
  24. */
  25. public class BlobTest {
  26. //向数据表customers中插入Blob类型的字段
  27. @Test
  28. public void testInsert() throws Exception{
  29. Connection conn = JDBCUtils.getConnection();
  30. String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
  31. PreparedStatement ps = conn.prepareStatement(sql);
  32. ps.setObject(1,"袁浩");
  33. ps.setObject(2, "yuan@qq.com");
  34. ps.setObject(3,"1992-09-08");
  35. FileInputStream is = new FileInputStream(new File("girl.jpg"));
  36. ps.setBlob(4, is);
  37. ps.execute();
  38. JDBCUtils.closeResource(conn, ps);
  39. }
  40. //查询数据表customers中Blob类型的字段
  41. @Test
  42. public void testQuery(){
  43. Connection conn = null;
  44. PreparedStatement ps = null;
  45. InputStream is = null;
  46. FileOutputStream fos = null;
  47. ResultSet rs = null;
  48. try {
  49. conn = JDBCUtils.getConnection();
  50. String sql = "select id,name,email,birth,photo from customers where id = ?";
  51. ps = conn.prepareStatement(sql);
  52. ps.setInt(1, 21);
  53. rs = ps.executeQuery();
  54. if(rs.next()){
  55. // 方式一:
  56. // int id = rs.getInt(1);
  57. // String name = rs.getString(2);
  58. // String email = rs.getString(3);
  59. // Date birth = rs.getDate(4);
  60. //方式二:
  61. int id = rs.getInt("id");
  62. String name = rs.getString("name");
  63. String email = rs.getString("email");
  64. Date birth = rs.getDate("birth");
  65. Customer cust = new Customer(id, name, email, birth);
  66. System.out.println(cust);
  67. //将Blob类型的字段下载下来,以文件的方式保存在本地
  68. Blob photo = rs.getBlob("photo");
  69. is = photo.getBinaryStream();
  70. fos = new FileOutputStream("zhangyuhao.jpg");
  71. byte[] buffer = new byte[1024];
  72. int len;
  73. while((len = is.read(buffer)) != -1){
  74. fos.write(buffer, 0, len);
  75. }
  76. }
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. }finally{
  80. try {
  81. if(is != null)
  82. is.close();
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. }
  86. try {
  87. if(fos != null)
  88. fos.close();
  89. } catch (IOException e) {
  90. e.printStackTrace();
  91. }
  92. JDBCUtils.closeResource(conn, ps, rs);
  93. }
  94. }
  95. }