Query tham đối (Parameterized query) nhận dữ liệu vào lúc thực hiện query. Tham đối biểu diễn bởi dấu ? trong câu lệnh SQL truy vấn.
Tạo query tham đối với lớp PreparedStatementobject.
package updatebook_preparestm;
import com.sun.rowset.CachedRowSetImpl;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.WebRowSet;
public class DataAccess {
private static final String URL =
"jdbc:derby://localhost:1527/library";
private DateFormat df = new SimpleDateFormat("yyyy-m-d");
public CachedRowSet getData(String sql){
CachedRowSet rs = null;
try {
Connection con = DriverManager.getConnection(URL);
rs = new CachedRowSetImpl();
rs.setCommand(sql);
rs.execute(con);
con.close();
}
catch (SQLException e){
System.out.println(e.getMessage());
}
return rs;
}
public void add(String sql, Book b){
try {
Connection con = DriverManager.getConnection(URL);
PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1, b.getBookID());
stm.setString(2, b.getTitle());
stm.setInt(3, b.getStatus());
stm.setString(4, df.format(b.getPublishingday()));
stm.setInt(5, b.getNumber());
stm.executeUpdate();
stm.close();
con.close();
}
catch(SQLException ex){
System.out.println(ex.getMessage());
}
}
public void edit(String sql, Book b){
try {
Connection con = DriverManager.getConnection(URL);
PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1, b.getTitle());
stm.setInt(2, b.getStatus());
stm.setString(3, df.format(b.getPublishingday()));
stm.setInt(4, b.getNumber());
stm.setString(5, b.getBookID());
stm.executeUpdate();
stm.close();
con.close();
}
catch(SQLException ex){
System.out.println(ex.getMessage());
}
}
public void delete(String sql, String bookID){
try {
Connection con = DriverManager.getConnection(URL);
PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1, bookID);
stm.executeUpdate();
stm.close();
con.close();
}
catch(SQLException ex){
System.out.println(ex.getMessage());
}
}
}