11_傳智播客JDBC_用jdbc訪問大段文本數據

 快捷鍵 F3 = ctrl+鼠標左鍵

package five.base;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import five.utils.Utils;

// 快捷鍵 F3 = ctrl+鼠標左鍵
public class BlobTest {

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
 
  //create(3, "c:/1.txt");
  read(3);

 }
 public static void  create( int id, String fileName) throws IOException{
  
  Connection connection = null;
  
  PreparedStatement ps = null;
  
  ResultSet rs = null;
  
  try {
   connection = Utils.getConnection();
   String sql = "insert into clob (id, test) values (?,?)";
   ps = connection.prepareStatement(sql);
   
   File file = new File(fileName);
   //裝飾模式 帶有緩衝區 讀取 效率高
   Reader reader = new BufferedReader(new FileReader(file));

   ps.setInt(1, id);
   // 前提 Ascii
   // parameterIndex - the first parameter is 1, the second is 2, ...
   // x - the Java input stream that contains the ASCII parameter value
   // length - the number of bytes in the stream
   //ps.setAsciiStream(2, x, length);
   
   // 字節流
    ps.setCharacterStream(2, reader, (int)file.length());
   int i = ps.executeUpdate();
   reader.close();
   System.out.println(i);
  } catch (SQLException e) {
   e.printStackTrace();
  }finally{
    Utils.free(connection, ps, rs);
  }
  
  
 }
 static void read(int id) throws Exception {

  Connection connection = null;
  PreparedStatement ps = null;
  ResultSet rs = null;

  try {
   connection = Utils.getConnection();
   String sql = "select test from clob";
   ps = connection.prepareStatement(sql);
   rs = ps.executeQuery();
   // 5 處理結果
   while (rs.next()) {
    //Clob clob =  rs.getClob(1);
    //Reader reader = clob.getCharacterStream();
    String test = rs.getString(1);
    System.out.println(test);
    Reader reader = rs.getCharacterStream("test");
    File file = new File("D:/cgz/dayByDayJdbc/Base_Bak.txt");
    Writer writer = new BufferedWriter(new FileWriter(file));
    
    char [] buff = new char[1024];
    for (int i = 0; (i = reader.read(buff)) > 0;) {
     writer.write(buff, 0, i);
    }
    writer.close();
    reader.close();
   }

  } finally {
   Utils.free(connection, ps, rs);
  }
 } 

}

發佈了48 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章