| 笨小孩's profile李宁PhotosBlogLists | Help |
|
April 16 JDBC 写 Clob 到数据库中(oracle 9i)创建一个表LOB_TEST
CREATE TABLE LOB_TEST ( A NUMBER(10), B BLOB, C CLOB ) 下面是java代码
package test; import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Random; /**
* A general-purpose SQL interpreter program. **/ public class ExecuteSQL { final static String url="jdbc:oracle:thin:@127.0.0.1:1521:test"; //orcl为数据库的SID final static String user="test"; final static String password="test"; final static String driver="oracle.jdbc.driver.OracleDriver"; final static String filePath="D:\\test\\test.txt"; public static void main(String[ ] args) { Connection conn = null; // Our JDBC connection to the database server PreparedStatement pstmt = null; Random random=new Random(); String num=String.valueOf(random.nextLong()); try { StringBuffer sql=new StringBuffer(); StringBuffer updateSql=new StringBuffer(); sql.append("INSERT INTO guof_test (A,C) values ('"+num+"',EMPTY_CLOB())"); updateSql.append("SELECT A,C from guof_test WHERE A= ? For update"); conn = getConnection(); conn.setAutoCommit(false); Statement state = conn.createStatement( ); state.executeUpdate(sql.toString()); state.close(); pstmt = conn.prepareStatement(updateSql.toString()); pstmt.setString(1, num); ResultSet rest = pstmt.executeQuery(); File parsed = new File(filePath); BufferedReader in =new BufferedReader(new InputStreamReader(new FileInputStream(parsed))); String readStr=null; if(rest.next()){ oracle.sql.CLOB clob = (oracle.sql.CLOB) rest.getClob("C"); Writer outStream = clob.getCharacterOutputStream(); try{ while((readStr=in.readLine())!=null){ outStream.write(readStr); } outStream.close(); }catch (IOException e) { e.printStackTrace(); } finally { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } conn.commit(); conn.setAutoCommit(true); } catch (Exception e) { e.printStackTrace();; } finally {
try { conn.close( ); } catch (Exception e) { } } } /**
* @return * @throws ClassNotFoundException * @throws SQLException */ public static Connection getConnection() throws ClassNotFoundException, SQLException { Connection conn; if (url == null) throw new IllegalArgumentException("No database specified"); if (driver != null) Class.forName(driver);
conn = DriverManager.getConnection(url, user, password); return conn; } } |
|
|