• java将字符串存入oracle的Blob中


    Blob内存放的是字节数组,需使用String的getBytes获得该字符串的字节数组(注意字符集编码),然后存入Blob。

    Oracle的Blob字段比较特殊,他比long字段的性能要好很多,可以用来保存例如图片之类的二进制数据。写入Blob字段和写入其它类型字段的方式非常不同,不能直接像插入其他普通类型数据一样插入Blob字段数据,因为Blob相当于一个大文件块,里面有游标cursor,你必须使用cursor对Blob进行操作,因而你在写入Blob之前,必须获得cursor。

    具体操作步骤是,先插入一个empty的Blob,这将创建一个Blob的cursor,然后你再把这个empty的Blob的cursor用select查询出来,这样通过两步操作,你就获得了Blob的cursor,可以真正地写入Blob数据了。

    public static void instertStringIntoBlob(String str) {
            try {
                //获得字符串的字节数组
                byte[] value = null;
                value = str.getBytes();
                //数据库连接
                Class.forName("oracle.jdbc.driver.OracleDriver");
                String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
                String username = "scott";
                String password = "scott";
                Connection con = DriverManager.getConnection(url, username, password);
                con.setAutoCommit(false);
                //插入空Blob,创建cursor
                String sql1 = "insert into test(id,content) values('999',empty_blob())";
                Statement statement = con.createStatement();
                statement.execute(sql1);
                //select获得cursor,并写入数据
                String sql2 = "select content from test where id=999 for update";
                PreparedStatement stmt = con.prepareStatement(sql2);
                ResultSet rs = stmt.executeQuery();
                OutputStream outStream = null;
                if (rs.next()) {
                    BLOB blob = (BLOB) rs.getBlob(1);
                    outStream = blob.getBinaryOutputStream();
                    outStream.write(value, 0, value.length);
                }
                outStream.flush();
                outStream.close();
                con.commit();
                con.close();
            } catch (Exception e) {
            }
        }
  • 相关阅读:
    关于软件工程的理解
    二人编程项目----五子棋
    多线程单元测试
    软件工程的 理解和问题
    教务管理系统软件设计说明书
    团队分组
    结对项目:贪吃蛇
    使用JUNIT等工具进行单元测试
    学习软件工程现存问题
    对unit4测试的初步认知
  • 原文地址:https://www.cnblogs.com/ohmyuan/p/10784645.html
Copyright © 2020-2023  润新知