JDBC Statement接口实现的execute方法

来源:互联网 发布:背景音乐提取软件 编辑:程序博客网 时间:2024/05/06 16:46
完整方法名为 boolean execute(String sql) throws SQLException;可见其返回值是Boolean类型的,那么什么时候返回的是true,什么时候返回的是false呢?首先我们知道boolean execute 允许执行查询语句、更新语句、DDL语句。返回值为true时,表示执行的是查询语句,可以通过getResultSet方法获取结果;返回值为false时,执行的是更新语句或DDL语句。下面拿一段源码举例:

package javademo;

import java.sql.*;

public class ConnectionDemo01 {
    private static final String driver = "org.gjt.mm.mysql.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/world?"
            + "characterEncoding=utf8&useSSL=false"; //防止在高版本MySQL上出现警告
    private static final String user = "你的用户名";
    private static final String password = "你的密码";

    public static void main(String[] args) throws Exception {
        Connection con = null;
        Statement sta = null;
        String sql="SELECT * FROM tdb_goods  WHERE goods_id=22";
        Class.forName(driver);

        con = DriverManager.getConnection(url, user, password);
        sta=con.createStatement();
        boolean a=sta.execute(sql);
        System.out.println(a);
        sta.close();
        con.close();

    }

}

输出:true,因为执行的是查询功能。

public class ConnectionDemo01 {
    private static final String driver = "org.gjt.mm.mysql.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/world?"
            + "characterEncoding=utf8&useSSL=false"; //防止在高版本MySQL上出现警告
    private static final String user = "你的用户名";
    private static final String password = "你的密码";

    public static void main(String[] args) throws Exception {
        Connection con = null;
        Statement sta = null;
        String sql="UPDATE  tdb_goods SET goods_id=21  WHERE goods_id=22";
        Class.forName(driver);

        con = DriverManager.getConnection(url, user, password);
        sta=con.createStatement();
        boolean a=sta.execute(sql);
        System.out.println(a);
        sta.close();
        con.close();

    }

}

输出:false,因为执行的是更新功能。
0 0
原创粉丝点击