Step By Step(Java JDBC篇) (三)

2014-11-24 03:19:38 · 作者: · 浏览: 16
prepareStatement(insertSQL);

26 pstmt.setString(1, "hello");

27 pstmt.executeUpdate();

28 pstmt.close();

29 //2. 取出刚刚插入的带有空blob数据的记录。

30 //注意:对于示例中的Oracle数据库,此次查询需要使用for update关键字,

31 //以保证在查询的同时锁定当前的记录。

32 String selectSQL = "select content from Test where name= for update";

33 pstmt = conn.prepareStatement(selectSQL);

34 pstmt.setString(1, "hello");

35 ResultSet rset = pstmt.executeQuery();

36 //3. 得到该BLOB字段数据操作的游标。

37 if (rset.next())

38 blob = (oracle.sql.BLOB) rset.getBlob(1);

39 //4. 开始准备读入待插入的测试文件的数据。

40 String fileName = "D:/Test.rar";

41 File f = new File(fileName);

42 FileInputStream fin = new FileInputStream(f);

43 System.out.println("file size = " + fin.available());

44 String updateSQL = "update Test set content= where name= ";

45 pstmt = conn.prepareStatement(updateSQL);

46 OutputStream out = blob.getBinaryOutputStream();

47 byte[] data = new byte[(int) fin.available()];

48 //从文件将数据读入到内存,之后在写入blob的底层流

49 fin.read(data);

50 out.write(data);

51 fin.close();

52 out.close();

53 //5. 更新准备的二进制数据到数据库

54 pstmt.setBlob(1, blob);

55 pstmt.setString(2, "hello");

56 pstmt.executeUpdate();

57 pstmt.close();

58 conn.commit();

59 String strDrop = "drop table Test";

60 stmt = conn.createStatement();

61 stmt.execute(strDrop);

62 } catch (SQLException e) {

63 e.printStackTrace();

64 } catch (IOException e) {

65 System.err.println(e.getMessage());

66 } catch (ClassNotFoundException e) {

67 e.printStackTrace();

68 } finally {

69 try {

70 conn.close();

71 } catch (SQLException e) {

72 e.printStackTrace();

73 }

74 }

75 }

76 }


作者 Stephen_Liu