Hỏi về PreparedStatement trong JDBC

Mọi người cho mình hỏi mình khai báo PrepareStatement xong sau đó setString các thứ sao mình phải nhấn build chương trình 2 lần thì lệnh setString mới thực hiện để update giá trị ạ ?

import java.sql.*;

    public class jdbc{
            public static Connection hj() {
                final String url="jdbc:mysql://localhost:3306/gg";
                final String user="root";
                final String password="thuy1234";

                try{
                    Class.forName("com.mysql.cj.jdbc.Driver");
                    Connection x=DriverManager.getConnection(url,user,password);
                    Statement y=null; y=x.createStatement();
                    String z="SELECT*from customers";
                    ResultSet rs = y.executeQuery(z);
                    String SQL = "UPDATE customers SET customerName=? WHERE customerID=?";
                    try (PreparedStatement k = x.prepareStatement(SQL)) {
                        k.setString(1, "popo");
                        k.setInt(2, 1);
                        k.execute();
                        // Buoc 5: Lay du lieu tu Result Set
                        while (rs.next()) {
                            // Lay du lieu boi su dung ten cot
                            int mssv = rs.getInt("customerID");
                            String ten = rs.getString("customerName");

                            // Hien thi cac gia tri
                            System.out.print("\ncustomerID: " + mssv);
                            System.out.println("\ncustomerName: " + ten);
                            System.out.print("\n=================");
                        }
                        k.close();
                    }
                    x.close();
                }
                catch (ClassNotFoundException e){
                    e.printStackTrace();
                }
                catch(SQLException e){
                    e.printStackTrace();
                }

                return null;
            }

            public static void main(String[] args) {
                Connection x= hj();
            }

    }

Do bạn lấy dữ liệu trước khi cập nhật.

  1. ResultSet rs = y.executeQuery(z); lấy dữ liệu trước.
  2. k.execute(); cập nhật.
  3. while (rs.next()) in dữ liệu đã lấy trước khi cập nhật từ bước 1.
5 Likes

ok anh, em cảm ơn nhiều ạ

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?