Liao Xuefeng Java15JDBC programming interfaces -2JDBC update -3JDBC

Update statements when the need to achieve through JDBC update statement, this time still be used by PreparedStatement objects directly into the update statement and pass the value of the placeholder by setObject, and finally through executeUpdate () can perform this update statement. executeUpdate () return value is int, on behalf of the number of records in line with the conditions.

1. update

    //update
    try(Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)){
        try(PreparedStatement ps = conn.prepareStatement("update students set name=? where id=?")){
            ps.setObject(1, "Bob");
            ps.setObject(2, 999);
            ps.executeUpdate();
        }
    }

1.1 update modified example JdbcUpdate.java

package com.feiyangedu.sample.pop3;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUpdate {
    static final String JDBC_URL = "jdbc:mysql://localhost:13306/test0828?useSSL=false&characterEncoding=utf8&serverTimeZone=UTC";
    static final String JDBC_USER="root";
    static final String JDBC_PASSWORD = "123456";

    public static  void main(String[] args) throws SQLException{
        List<Student> students = getAllStudents();
        for(Student student:students){
            System.out.println(student);
        }
        Student std = students.get(0);
        std.classId = new Long(2);
        std.name = "Alice";
        std.gender = "F";
        update(std);
        System.out.println("--变更后--");
        students = getAllStudents();
        for(Student student:students){
            System.out.println(student);
        }
    }

    static void update(Student std) throws SQLException{
        try(Connection conn = getConnection()){
            try(PreparedStatement ps = conn.prepareStatement("update students set class_id=?,name=?,gender=? where id=?")){
                ps.setObject(1, std.classId);
                ps.setObject(2, std.name);
                ps.setObject(3, std.gender);
                ps.setObject(4, std.id);
                int n = ps.executeUpdate();
                System.out.println(n+"条记录发生变更.");
            }
        }
    }
    static List<Student> getAllStudents() throws SQLException{
        try(Connection conn = getConnection()){
            try(PreparedStatement ps = conn.prepareStatement("select * from students")){
                ResultSet rs = ps.executeQuery();
                List<Student> list = new ArrayList<>();
                while(rs.next()){
                    Long id = rs.getLong("id");
                    Long classId = rs.getLong("class_id");
                    String name = rs.getString("name");
                    String gender = rs.getString("gender");
                    Student std = new Student(id,classId,name,gender);
                    list.add(std);
                }
                return list;
            }
        }
    }
    static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_URL,JDBC_USER,JDBC_PASSWORD);
    }
}

2. delete statement is the same

    try(Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)){
        try(PreparedStatement ps = conn.prepareStatement("delete from student where id=?")){
            ps.setObject(1, 999);
            int n = ps.executeUpdate(); //返回结果为删除记录的数量
        }
    }

2.1 delete example JdbcDelete.java

package com.feiyangedu.sample.pop3;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcDelete {
    static final String JDBC_URL = "jdbc:mysql://localhost:13306/test0828?useSSL=false&characterEncoding=utf8&serverTimeZone=UTC";
    static final String JDBC_USER="root";
    static final String JDBC_PASSWORD = "123456";
    public static void main(String[] args) throws SQLException{
        List<Student> students = getAllStudents();
        for(Student student:students){
            System.out.println(student);
        }
        long studentId = students.get(students.size()-1).id; //查找最后1条记录的id
        delete(studentId);
        System.out.println(studentId+"删除成功");
        students = getAllStudents();
        for(Student student:students){
            System.out.println(student);
        }
    }
    static void delete(long studentId) throws SQLException{
        try(Connection conn = getConnection()){
            try(PreparedStatement ps = conn.prepareStatement("delete from students where id=?")){
                ps.setObject(1, studentId);
                ps.executeUpdate();
            }
        }
    }
    static List<Student> getAllStudents() throws SQLException {
        try(Connection conn = getConnection()){
            try(PreparedStatement ps = conn.prepareStatement("select * from students")){
                ResultSet rs = ps.executeQuery();
                List<Student> list = new ArrayList<>();
                while(rs.next()){
                    long id = rs.getLong("id");
                    long classId = rs.getLong("class_id");
                    String name = rs.getString("name");
                    String gender = rs.getString("gender");
                    Student std = new Student(id,classId,name,gender);
                    list.add(std);
                }
                return list;
            }
        }
    }
    static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_URL,JDBC_USER,JDBC_PASSWORD);
    }
}

3. insert statement

3.1 simply insert data

    try(Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)){
        try(PreparedStatement ps = conn.prepareStatement("insert into student(id, class_id, name, gender) values(?, ?, ?, ?)")){
            ps.setObject(1, 999);
            ps.setObject(2, 1);
            ps.setObject(3, "Bob");
            ps.setObject(4, "M");
            int n = ps.executeUpdate();
        }
    }

After growing 3.2 insert obtained from id

    try(Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)){
        try(PreparedStatement ps = conn.prepareStatement("insert into students(class_id, name, gender) values (?, ? ,?)",Statement.RETURN_GENERATED_KEYS)){
            //我们并没有指定id的值,而是由数据库自动生成。我们往往需要获取数据库自动生成主键的值。这就需要再调用preparedStatement的时候传入一个常量Statement.RETURN_GENERATED_KEYS,表示需要返回数据库生成的主键。在执行executeUpdate()方法以后,我们可以通过getGeneratedKeys()获取一个ResultKey对象。这个对象包含了数据库自动生成主键的值,因为我们只有1条插入的数据,因此获得第一条
            ps.setObject(1, 1);
            ps.setObject(2, "Bob");
            ps.setObject(3, "M");
            int n = ps.executeUpdate();
            try(ResultSet rs = ps.getGeneratedKeys()){
                if(rs.next()){
                    long id = rs.getLong(1);
                }
            }
        }
    }

3.3 insert JdbcInsert.java Sample Code

package com.feiyangedu.sample.pop3;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcInsert {
    static final String JDBC_URL = "jdbc:mysql://localhost:13306/test0828?useSSL=false&characterEncoding=utf8&serverTimeZone=UTC";
    static final String JDBC_USER="root";
    static final String JDBC_PASSWORD = "123456";

    public static  void main(String[] args) throws SQLException {
        List<Student> students = getAllStudents();
        for(Student student:students){
            System.out.println(student);
        }
        insertWithAutoGeneratedId(new Student(2,"Tim","M"));
        insertWithId(new Student(999,2,"Bob","M"));
        System.out.println("插入完成");
        students = getAllStudents();
        for(Student student:students){
            System.out.println(student);
        }
    }

    static void insertWithId(Student std) throws SQLException{
        try(Connection conn = getConnection()){
            try(PreparedStatement ps = conn.prepareStatement("insert into students values (?, ?, ?, ?)")){
                ps.setObject(1, std.id);
                ps.setObject(2, std.classId);
                ps.setObject(3, std.name);
                ps.setObject(4, std.gender);

                int n = ps.executeUpdate();
                System.out.println(n+"条记录被插入");
            }
        }
    }
    static void insertWithAutoGeneratedId(Student std) throws SQLException{
        try(Connection conn = getConnection()){
            try(PreparedStatement ps = conn.prepareStatement("insert into students(class_id, name, gender) values (?, ?, ?)",Statement.RETURN_GENERATED_KEYS)){ //需要返回数据库自动生成主键的值
                ps.setObject(1, std.classId);
                ps.setObject(2, std.name);
                ps.setObject(3, std.gender);
                int n = ps.executeUpdate();
                System.out.println(n+"条记录被插入");
                try(ResultSet rs = ps.getGeneratedKeys()){ //通过getGeneratedKeys()拿到主键
                    if(rs.next()){
                        long id = rs.getLong(1);
                        std.id = id;
                    }
                }
            }
        }
    }
    static List<Student> getAllStudents() throws SQLException{
        try(Connection conn = getConnection()){
            try(PreparedStatement ps = conn.prepareStatement("select * from students")){
                ResultSet rs = ps.executeQuery();
                List<Student> list = new ArrayList<>();
                while(rs.next()){
                    long id = rs.getLong("id");
                    long classId = rs.getLong("class_id");
                    String name = rs.getString("name");
                    String gender = rs.getString("gender");
                    Student std = new Student(id,classId,name,gender);
                    list.add(std);
                }
                return list;
            }
        }
    }
    static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_URL,JDBC_USER,JDBC_PASSWORD);
    }

}

4 JDBC update summary

  • Use the executeUpdate PreparedStatement () update
  • Update includes update, insert, delete statement
  • The result is int update

Guess you like

Origin www.cnblogs.com/csj2018/p/11441945.html