首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >getBinaryStream(索引)问题

getBinaryStream(索引)问题
EN

Stack Overflow用户
提问于 2014-09-29 15:45:23
回答 3查看 595关注 0票数 2

当我从数据库中读取blob数据时,我得到了null值。可能的问题是什么?有人能帮我这个忙吗?

代码语言:javascript
运行
复制
 Connection con = null;
 PreparedStatement psStmt = null;
 ResultSet rs = null;


try {
    try {

        Class.forName("oracle.jdbc.driver.OracleDriver");


            } catch (ClassNotFoundException e) {

                e.printStackTrace();

            }
            con = 

DriverManager.getConnection("jdbc:oracle:thin:@MyDatabase:1535:XE","password","password");

            System.out.println("connection established"+con);

            psStmt = con
                    .prepareStatement("Select Photo from Person where Firstname=?");

            int i = 1;

            psStmt.setLong(1, "Nani");

            rs = null;

            rs = psStmt.executeQuery();

            InputStream inputStream = null;

            while (rs.next()) {

                inputStream = rs.getBinaryStream(1);

                //Blob blob = rs.getBlob(1);

                //Blob blob1 = (Blob)rs.getObject(1);

                //System.out.println("blob length   "+blob1);//rs.getString(1);

            }


            System.out.println("bytessssssss   "+inputStream);//here i am getting null value.


        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }
EN

Stack Overflow用户

发布于 2014-09-29 16:36:57

最明显的错误是使用setLong而不是setString。

然而,有一种做法是致命的:提前声明。在其他语言中,这是一个很好的实践,但在java中,应该声明尽可能接近。

这缩小了你会发现错误的作用域!即inputStream在失败的rs.next()之后被调用--在循环之外。也许是因为找不到任何记录。

这种做法,声明尽可能接近可行,也有助于在这里使用try- with -resources来自动关闭语句和结果集。

代码语言:javascript
运行
复制
Connection con = null;
try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection(
            "jdbc:oracle:thin:@MyDatabase:1535:XE","password","password");
    System.out.println("connection established"+con);
    try (PreparedStatement psStmt = con.prepareStatement(
            "Select Photo from Person where Firstname=?")) {
        int i = 1;
        psStmt.setString(1, "Nani");
        try (ResultSet rs = psStmt.executeQuery()) {
            while (rs.next()) {
                try (InputStream inputStream = rs.getBinaryStream(1)) {
                    //Blob blob = rs.getBlob(1);
                    //Blob blob1 = (Blob)rs.getObject(1);
                    //System.out.println("blob length   "+blob1);//rs.getString(1);
                    Files.copy(inputStream, Paths.get("C:/photo-" + i + ".jpg"));
                }
                ++i;
            }
            //ERROR System.out.println("bytessssssss   "+inputStream);
        } // Closes rs.
    } // Closes  psStmt.
}
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26094885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档