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();
}
}