1. 程式人生 > >通過JDBC向oracle資料庫中插入Clob大物件

通過JDBC向oracle資料庫中插入Clob大物件

好記性不如爛筆頭,今天剛剛學過Clob的插入和查詢,寫篇部落格,以備後用

首先建立一個包含大物件的表

create table data(
   id varchar2(20),
   content clob
 );

然後通過JDBC連線資料庫並插入Clob大物件 不多廢話,程式碼如下:

import java.sql.*;

public class  Test{

	public static void main(String []args){
		try{

			Class.forName("oracle.jdbc.driver.OracleDriver");         //載入驅動
			String url = "jdbc:oracle:thin:@localhost:1521:orcl";
			String user = "scott";
			String password = "trigger";
			Connection con = DriverManager.getConnection(url, user, password);  //連線資料庫

			con.setAutoCommit(false);

			/*
			* 資料庫連線完成,接下來我們要把大象放進冰箱了
			*
			* */
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			Clob clob = null;

//			先插入空的Clob物件                                                  --第一步
			String sql="insert into data(id,content) values(?,empty_clob())";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1,"123456");
			pstmt.execute();
			pstmt.close();

//			然後將這個物件取出來,用來獲取Clob物件                               --第二步
			String sql2 = "select content from data where id = ? for update";
			pstmt = con.prepareStatement(sql2);
			pstmt.setString(1,"123456");
			rs = pstmt.executeQuery();
			if(rs.next()){
				clob = rs.getClob(1);
			}
			rs.close();
			pstmt.close();


//			將資料插入到clob中                                                  --第三步
			String str  = "這是我要插入的資料,待會我還會把它取出來";
			clob.setString(1,str);

//			從資料庫中取出自己插入的資料
			String sql3 = "select * from data where id=?";
			pstmt = con.prepareStatement(sql3);
			pstmt.setString(1,"123456");
			rs = pstmt.executeQuery();
			if(rs.next()){
				Clob c = rs.getClob("content");
				String value = c.getSubString(1,(int)c.length());
				System.out.println(value);
			}
			rs.close();
			pstmt.close();
			
			con.commit();

		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

結果如下: 在這裡插入圖片描述 資料庫中資料如下: 在這裡插入圖片描述