目录
execute():几乎可以执行任何SQL语句,返回值是boolean值,表明该SQL语句是否返回ResultSet对象
boolean值:
-
- import java.sql.*;
- public class TestDemo {
-
- public static void main(String[] args) {
-
- JDBCDemo jdbc = new JDBCDemo();
- }
- }
-
- class JDBCDemo{
- public JDBCDemo() {
-
- try {
- // 1.
- Class.forName("com.mysql.cj.jdbc.Driver");
-
- // 2.
- Connection con = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/de?characterEncoding=gb2312&serverTimezone=UTC&useSSL=false", "root", "root");
-
- // 3.
- Statement stmt = con.createStatement();
-
- // 4.
- String sql = "SELECT * FROM tb_student"; // sql语句
- Boolean bool = stmt.execute(sql);
- System.out.println("bool = " + bool);
- if (bool) {
- ResultSet rs = stmt.getResultSet(); // 获取ResultSet对象
- // 5.
- while(rs.next()){
- int studentNo = rs.getInt(1); // 指定第几列
- String studentName = rs.getString("studentName"); // 指定列名称
- System.out.println(studentNo + "---" + studentName);
- }
-
- // 6.
- rs.close();
- stmt.close();
- con.close();
- }
- } catch (SQLException | ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
executeUpdate():用于执行DDL和DML语句,返回值为所影响的行数
executeUpdate增强版(Java8新增):executeLargeUpdate(),返回值为long类型,适用于DML语句的记录超过Interger.MAX_VALUES的情况
- import java.sql.*;
- public class TestDemo {
-
- public static void main(String[] args) throws ClassNotFoundException, SQLException {
-
- JDBCDemo jdbc = new JDBCDemo();
- }
- }
-
- class JDBCDemo{
- public JDBCDemo() throws SQLException, ClassNotFoundException {
-
- // 1.
- Class.forName("com.mysql.cj.jdbc.Driver");
-
- // 2.
- Connection con = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/de?characterEncoding=gb2312&serverTimezone=UTC&useSSL=false", "root", "root");
-
- // 3.
- Statement stmt = con.createStatement();
-
- // 4.
- String sql = "UPDATE tb_student SET studentName='狗蛋' WHERE studentNo=2013110101"; // sql语句
- int res = stmt.executeUpdate(sql);
-
- // 5.
- System.out.println( "所影响的记录行数:" + res );
-
-
- // 6
- stmt.close();
- con.close();
- }
-
- }