Pst對象保存大對象: BLOB - Binaray Larg Object - > 大的二進制類型 > 4G CLOB - Character larg Object - > 大的字符類型 - > 4Gsql
1:保存一個圖片到數據表中去 – Blob create table users( name varchar(30), img blob );code
@Test public void testBlob() throws Exception { Connection con = ConnUtils.getCon(); String sql = "insert into users values(?,?)"; PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, "Jerry"); pst.setBinaryStream(2, new FileInputStream("D:/相片/SAM_1720.JPG")); pst.execute(); pst.close(); con.close(); } /** * 查詢出圖片,保存到一個指定的目錄下 */ @Test public void testQueryBlob() throws Exception { Statement st = con.createStatement(); // 在公司裏面開發,禁止使用 * ResultSet rs = st.executeQuery("select name,img from users where name='Jerry'"); rs.next(); //獲取字節流 InputStream in = rs.getBinaryStream("img"); Files.copy(in, new File("d:/a/a.jpg").toPath(), StandardCopyOption.REPLACE_EXISTING); //如下是獲取Blob對象 Blob blob= rs.getBlob("img"); in = blob.getBinaryStream(); rs.close(); st.close(); }
2:保存大的文本到表中去Clob對象
create table notes( id int, text clob );圖片
/** * 讀取大的文本類型 */ @Test public void testReadCLOB() throws Exception{ String sql = "select * from notes"; PreparedStatement pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(); if(rs.next()){ InputStream in = rs.getAsciiStream("text"); byte[] bs = new byte[1024]; int len =0; while((len=in.read(bs))!=-1){ String str = new String(bs,0,len); System.err.print(str); } in.close(); } pst.close(); }