Parsing the detailed explanation of clob field of jdbc processing oracle
- 2021-07-18 09:16:22
- OfStack
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ClobUtil {
/**
*
* @param insertSQL Insert sql Statement Have clob Field, the value must be set to empty_clob() Function Example :insert into ba valus(1,empty_clob())
* @param updateSQL Query statement with modification , Conditional judgment should be added . Example: select * from BA where ba_id = '"+ba.getBA_id()+"' for update
* @param con Database link
* @param bigString To insert clob Value
* @param updateColumn The name of the table field to insert
* @return
* @throws SQLException
*/
public static Boolean clobInsert(String insertSQL,String updateSQL,Connection con,String bigString,String updateColumn ) throws SQLException{
// Result set
ResultSet rs = null;
// Insert the sql
String query = insertSQL;
// Setting No Automatic Submission
con.setAutoCommit(false);
// Definition preprocessing
java.sql.PreparedStatement pstmt = con.prepareStatement( query);
// Execute an insert statement
pstmt.executeUpdate();
// Empty
pstmt = null;
// Execute a change
query = updateSQL;
// Displays the execution of the select
pstmt = con.prepareStatement(query);
rs = pstmt.executeQuery();
// Process the result set in a stream way
if(rs.next())
{
// Get the specified clob Field
oracle.sql.CLOB singnaturedateClob = (oracle.sql.CLOB)rs.getClob(updateColumn);
// Put clob Fields are placed in the output stream
BufferedOutputStream out = new BufferedOutputStream(singnaturedateClob.getAsciiOutputStream());
// Determine whether the incoming data is empty
if(bigString!=null){
try{
// Convert the data to be saved into an input stream
InputStream is = (InputStream)(new ByteArrayInputStream(bigString.getBytes()));
copyStream( is, out );
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
rs.close();
con.commit();
return true;
}
/**
* Write the input stream to the output stream
* @param is Input stream
* @param os Output stream
* @throws IOException
*/
public static void copyStream( InputStream is, OutputStream os )
throws IOException
{
byte[] data = new byte[4096];
int readed = is.read(data);
while (readed != -1)
{
os.write(data,0,readed);
readed = is.read(data);
}
}
/**
* Pass Clob Object returns a string
* @param c
* @return
*/
public static String getClobString(Clob c) {
try {
Reader reader=c.getCharacterStream();
if (reader == null) {
return null;
}
StringBuffer sb = new StringBuffer();
char[] charbuf = new char[4096];
for (int i = reader.read(charbuf); i > 0; i = reader.read(charbuf)) {
sb.append(charbuf, 0, i);
}
return sb.toString();
} catch (Exception e) {
return "";
}
}
}