CLOB的全名是Charachter Large Object,用于存储大量的文字数据。
有时你需要将长文本保存到数据库表里,比方说长篇小说,同时有加密要求,即DBA不能看到内容。
JDBC的CLOB数据类型正是其中的解决方案之一。
保存文件
下面的示例演示了如何将文本文件内容保存到数据库表里。
首先,建立一张表。数据类型选择TEXT类型,也可以选择MEDIUMTEXT或LONGTEXT类型。
CREATE TABLE bigtb (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(45) COLLATE utf8_bin DEFAULT NULL,
file longtext COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
本例子中使用的是MariaDB。
插入数据完整代码:
public static void main(String[] args) {
String url = “jdbc:mysql://127.0.0.1:3306/northwind
?useUnicode=true&characterEncoding=utf-8”;
String user = “northwind”;
String password = “northwind”;
String classpath = App8.class.getResource("/").getPath();String pathname =classpath+"/demo/小程序.txt";BufferedReader br = null;StringBuffer sb = new StringBuffer();try {// Fix Chinese garbledbr = new BufferedReader(new InputStreamReader(newFileInputStream(pathname), "UTF-8"));String line;while ((line = br.readLine()) != null) {sb.append(line).append("\n");}} catch (IOException e) {e.printStackTrace();}try (Connection connection = DriverManager.getConnection(url, user, password)) {Clob clob = connection.createClob();clob.setString(1, sb.toString() );String sql = "insert into bigtb (name,file) values(?,?)";PreparedStatement statement = connection.prepareStatement(sql);statement.setString(1, "M");statement.setClob(2, clob);statement.executeUpdate();statement.close();} catch (SQLException e) {e.printStackTrace();
}
}
变量url的值有一段?useUnicode=true&characterEncoding=utf-8的内容,这用于指出字符编码为UTF-8,这样便能支持中文。
App7.class.getResource("/").getPath(); 用于获取classes目录的绝对路径。
String pathname =classpath+"/demo/小程序.txt"; 拼接文件路径,文件小程序.txt放在包demo内。
关键代码 statement.setClob(2, clob); 设置第二个参数为CLOB类型。
读取内容
读取使用getClob()方法。
public static void main(String[] args) {
String url = “jdbc:mysql://127.0.0.1:3306/northwind
?useUnicode=true&characterEncoding=utf-8”;
String user = “northwind”;
String password = “northwind”;
String content = null;
try (Connection connection = DriverManager.getConnection(url, user, password)) {String sql = "select * from bigtb where id=?";PreparedStatement statement = connection.prepareStatement(sql);statement.setInt(1, 7);ResultSet rs = statement.executeQuery();while (rs.next()) {Clob clob = rs.getClob("file");if (clob != null) {content = clob.getSubString((long) 1, (int) clob.length());}System.out.println(content);}statement.close();} catch (SQLException e) {e.printStackTrace();
}
}