stmt.execute(sql)的返回值

1、stmt.execute(sql)的返回值

执行sql是一条插入或更新语句,不能通过statement.execute(sql)的返回值判断是否插入或更新成功。
插入语句或更新语句,返回的不是执行成功与否的结果。
想要获得插入是否成功的信息,可选方法是在执行插入动作后,再执行一句查询操作。

    public int execOther(String sql)
    {
        int re=0;
        try{
            Connection conn=getConnection();
            Statement stmt=conn.createStatement();
            boolean result=stmt.execute(sql);
            re=1;
            System.out.println("+++++sql:"+sql);
            stmt.close();
            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return re;
    }

虽然插入成功了,但result打印出来是false.

备注:

Java API Statement类的execute的确返回Boolean 型。
他指的是否返回ResultSet对象;
对插入,更新,来说没有返回对象所以就是false!!!

sql是insert、update之类的不返回结果集的语句,或者虽然是select语句,但是没有查询到相应结果集的时候,则返回false。

sql是select语句,且成功查询到相应记录,则返回true;

2、ResultSet rs=statement.executeQuery(sql);

执行查询语句返回的是结果集。

    public String execSelect(String sql)
    {
        String result="";
        Connection conn=getConnection();
        try{
            Statement statement=conn.createStatement();
            ResultSet rs=statement.executeQuery(sql);
            int columnCount=rs.getMetaData().getColumnCount();
            System.out.println("+++++sql:"+sql);
            while (rs.next()){
                String columnContent="";
                for(int i=0;i<columnCount;i++){
                    columnContent +="\t"+rs.getString(i+1);
                }
                result +=columnContent+"\n";
            }
            //System.out.println(result);
            rs.close();
            statement.close();
            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

猜你喜欢

转载自blog.csdn.net/fen_fen/article/details/131591075
今日推荐