028_jdbc-mysql大文本
生活随笔
收集整理的這篇文章主要介紹了
028_jdbc-mysql大文本
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 例如我們存儲一篇文章、大量文字, 就需要用到大文本。
2. MySQL的大文本類型有: tinytext, text, mediumtext, longtext。
3. JDBC中我們用PrepareStatement的SetClob和SetNClob來設置大文本存儲;使用GetClob和GetNClob獲取大文本數據。
4. 新建一個JDBC_CLOB工程, 使用我們之前的JDBCUtil.java和jdbc.properties屬性文件, 同時在Resources目錄下存放一個文本文件
5. 創建TextDao.java接口
package com.lywgames.dao;import java.io.Reader;public interface TextDao {public void createTable();public void insert(Reader reader);public void findAll();public void deleteTable(); }6. 創建TextDaoImpl.java來對大文本進行存儲和獲取
package com.lywgames.dao.impl;import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.lywgames.dao.TextDao; import com.lywgames.util.JDBCUtil;public class TextDaoImpl implements TextDao {@Overridepublic void createTable() {Connection conn = null; PreparedStatement ps = null;try {conn = JDBCUtil.getConn(); ps = conn.prepareStatement("create table dawenbwen(id int(11) not null auto_increment, introduce text, primary key(id))");ps.execute();} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtil.release(conn, ps);}}@Overridepublic void insert(Reader reader) {Connection conn = null; PreparedStatement ps = null;try {conn = JDBCUtil.getConn(); ps = conn.prepareStatement("insert into dawenbwen values(null, ?)");ps.setClob(1, reader);ps.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtil.release(conn, ps);}}@Overridepublic void findAll() {Connection conn = null; PreparedStatement ps = null;ResultSet rs = null;try {conn = JDBCUtil.getConn(); ps = conn.prepareStatement("select * from dawenbwen");rs = ps.executeQuery();while(rs.next()){int id = rs.getInt(1);String tempText = null;StringBuffer sb = new StringBuffer();Clob clob = rs.getClob(2);Reader reader = clob.getCharacterStream();BufferedReader br = new BufferedReader(reader);while((tempText = br.readLine()) != null) {sb.append(tempText);}System.out.println(id + " " + sb.toString());}} catch (SQLException | IOException e) {e.printStackTrace();} finally {JDBCUtil.release(conn, ps, rs);}}@Overridepublic void deleteTable() {Connection conn = null; PreparedStatement ps = null;try {conn = JDBCUtil.getConn(); ps = conn.prepareStatement("drop table dawenbwen");ps.execute();} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtil.release(conn, ps);}} }7. 運行程序, 查看結果
總結
以上是生活随笔為你收集整理的028_jdbc-mysql大文本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 027_jdbc-mysql几个常用的日
- 下一篇: 029_jdbc-mysql二进制数据