![](https://img-blog.csdnimg.cn/85c079e7ae0f4a57b9e23acc46ec8e36.png)
本文为大家分享一篇关于MySQL存储文本和图片的方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随微点阅读小编来看看吧
Oracle中大文本数据类型
1 2 | Clob 长文本类型 (MySQL中不支持,使用的是text) Blob 二进制类型 |
MySQL数据库
1 2 3 4 5 6 | Text 长文本类型 TINYTEXT: 256 bytes TEXT: 65,535 bytes => ~64kb MEDIUMTEXT: 16,777,215 bytes => ~16MB LONGTEXT: 4,294,967,295 bytes => ~4GB Blob 二进制类型 |
例如:
建表
1 2 3 4 5 | CREATE TABLE test( id INT PRIMARY KEY AUTO_INCREMENT, content LONGTEXT, -- 文本字段 img LONGBLOB -- 图片字段 ); |
存储文本时是以字符类型存储,存储图片时是以二进制类型存储,具体使用的设置参数方法,和获取数据方法不同。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // 存储文本时 // 存储时,设置参数为字符流 FileReader reader pstmt.setCharacterStream( 1 , reader); // 获取参数时 // 方式1: Reader r = rs.getCharacterStream( "content" ); // 获取长文本数据, 方式2: System.out.print(rs.getString( "content" )); // 存储二进制图片时 // 设置参数为2进制流 InputStream in pstmt.setBinaryStream( 1 , in); // 获取2进制流 InputStream in = rs.getAsciiStream( "img" ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | /** * 保存照片 * */ @Test public void test2(){ String sql = "insert into test(img) values(?)" ; try { con = JDBCUtil.getConnection(); pstmt = con.prepareStatement(sql); // 设置参数 // 获取文本 File file = new File( "f:/a.jpg" ); InputStream in = new FileInputStream(file); // 设置参数为2进制流 pstmt.setBinaryStream( 1 , in); // 执行sql pstmt.executeUpdate(); in.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { JDBCUtil.close(con, pstmt); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 获取照片 * */ @Test public void test3(){ String sql = "select * from test where id=?;" ; try { con = JDBCUtil.getConnection(); pstmt = con.prepareStatement(sql); // 设置参数 pstmt.setInt( 1 , 2 ); // 执行查询 rs = pstmt.executeQuery(); while (rs.next()){ byte [] buff = new byte [ 1024 ]; InputStream in = rs.getAsciiStream( "img" ); int l= 0 ; OutputStream out = new FileOutputStream( new File( "f:/1.jpg" )); while ((l=in.read(buff))!=- 1 ){ out.write(buff, 0 , l); } in.close(); out.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { JDBCUtil.close(con, pstmt); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值!
转自:微点阅读 https://www.weidianyuedu.com