一、基本概念
大数据也称之为LOB(Large Objects),LOB又分为:clob和blob,clob用于存储大文本,blob用于存储二进制数据,例如图像、声音、二进制文等。
在实际开发中,有时是需要用程序把大文本或二进制数据直接保存到数据库中进行储存的。
对MySQL而言只有blob,而没有clob,mysql存储大文本采用的是Text,Text和blob分别又分为:
TINYTEXT、TEXT、MEDIUMTEXT和LONGTEXT
TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB
二、搭建测试环境
2.1、搭建的测试项目架构
如下:
2.2、编写db.properties配置文件
2.3、编写JdbcUtils工具类
package me.tanlei.jdbc; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class jdbcUtils { private static String driver = null; private static String url = null; private static String username = null; private static String password = null; static { try { // 读取db.properties文件中的数据库连接信息 InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); // 从输入字节流读取属性列表(键,值) properties.load(in); // 获取数据库连接驱动 driver = properties.getProperty("driver"); // 获取数据库连接URL地址 url = properties.getProperty("url"); // 获取数据库连接用户名 username = properties.getProperty("username"); // 获取数据库连接密码 password = properties.getProperty("password"); // 加载数据库驱动 Class.forName(driver); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } /* * 获取数据库连接对象 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } /* * 释放资源 */ public static void release(Connection connection, Statement statement, ResultSet resultSet) { if (resultSet != null) { try { // 关闭存储查询结果的ResultSet对象 resultSet.close(); } catch (Exception e) { e.printStackTrace(); } resultSet = null; } if (statement != null) { try { // 关闭负责执行SQL命令的Statement对象 statement.close(); } catch (Exception e) { e.printStackTrace(); } } if (connection != null) { try { // 关闭Connection数据库连接对象 connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
三、使用JDBC处理MySQL的大文本
对于MySQL中的Text类型,可调用如下方法设置
PreparedStatement.setCharacterStream(index, reader, length);//注意length长度须设置,并且设置为int型
对MySQL中的Text类型,可调用如下方法获取
1.reader = resultSet. getCharacterStream(String columnLabel);
2. string s = resultSet.getString(String columnLabel);
3.1、 测试范例
1、编写SQL测试脚本
create database jdbcstudy; use jdbcstudy; create table testclob ( id int primary key auto_increment, resume text );
2、编写测试代码如下:
package me.tanlei.demo; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.Test; import com.sun.crypto.provider.RSACipher; import me.tanlei.jdbc.jdbcUtils; public class JdbcOperaClob { /** * 向数据库中插入大文本数据 * * @throws IOException */ @Test public void add() throws IOException { Connection connection = null; PreparedStatement pStatement = null; ResultSet rSet = null; Reader reader = null; try { connection = jdbcUtils.getConnection(); String sql = "insert into testclob(resume) values(?)"; pStatement = connection.prepareStatement(sql); String path = JdbcOperaClob.class.getClassLoader().getResource("data.txt").getPath(); // 将"tanlei"替换回空格 path = path.replaceAll("tan", " "); File file = new File(path); reader = new FileReader(file); pStatement.setCharacterStream(1, reader, (int) file.length()); int num = pStatement.executeUpdate(); if (num > 0) { System.out.println("插入成功"); } // 关闭流 reader.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { jdbcUtils.release(connection, pStatement, rSet); } } /** * 读取数据库中的大文本数据 * * @throws IOException */ @Test public void read() throws IOException { Connection connection2 = null; PreparedStatement pStatement2 = null; ResultSet resultSet = null; try { connection2 = jdbcUtils.getConnection(); String sql = "select resume from testclob where id=2"; pStatement2 = connection2.prepareStatement(sql); resultSet = pStatement2.executeQuery(); String contentStr = ""; String content = ""; if (resultSet.next()) { // 使用resultSet.getString("字段名")获取大文本数据的内容 content = resultSet.getString("resume"); // 使用resultSet.getCharacterStream("字段名")获取大文本数据的内容 Reader reader = resultSet.getCharacterStream("resume"); char buffer[] = new char[1024]; int len = 0; FileWriter out = new FileWriter("D:\1.txt"); while ((len = reader.read(buffer)) > 0) { contentStr += new String(buffer); out.write(buffer, 0, len); } out.close(); reader.close(); } System.out.println(content); System.out.println("-----------------------------------------------"); System.out.println(contentStr); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
四、使用JDBC处理MySQL的二进制数据
对于MySQL中的BLOB类型,可调用如下方法设置:
PreparedStatement. setBinaryStream(i, inputStream, length);
对MySQL中的BLOB类型,可调用如下方法获取:
InputStream in = resultSet.getBinaryStream(String columnLabel);
InputStream in = resultSet.getBlob(String columnLabel).getBinaryStream();
4.1、 测试范例
1、编写SQL测试脚本
create table testblob ( id int primary key auto_increment, image longblob );
2、编写测试代码如下:
package me.gacl.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import me.gacl.utils.JdbcUtils; import org.junit.Test; /** * @ClassName: JdbcOperaClob * @Description: 使用JDBC操作MySQL的二进制数据(例如图像、声音、二进制文) * */ public class JdbcOperaBlob { /** * @Method: add * @Description:向数据库中插入二进制数据 * */ @Test public void add(){ Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "insert into testblob(image) values(?)"; st = conn.prepareStatement(sql); //这种方式获取的路径,其中的空格会被使用“%20”代替 String path = JdbcOperaBlob.class.getClassLoader().getResource("01.jpg").getPath(); //将“%20”替换会空格 path = path.replaceAll("%20", " "); File file = new File(path); FileInputStream fis = new FileInputStream(file);//生成的流 st.setBinaryStream(1, fis,(int) file.length()); int num = st.executeUpdate(); if(num>0){ System.out.println("插入成功!!"); } fis.close(); }catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.release(conn, st, rs); } } /** * @Method: read * @Description: 读取数据库中的二进制数据 * */ @Test public void read() { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); String sql = "select image from testblob where id=?"; st = conn.prepareStatement(sql); st.setInt(1, 1); rs = st.executeQuery(); if (rs.next()) { //InputStream in = rs.getBlob("image").getBinaryStream();//这种方法也可以 InputStream in = rs.getBinaryStream("image"); int len = 0; byte buffer[] = new byte[1024]; FileOutputStream out = new FileOutputStream("D:\1.jpg"); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); out.close(); } } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtils.release(conn, st, rs); } } }