java,servlet中的PreparedStatement 接口繼承了Statement,並與之在兩方面有所不同:有人主張,在JDBC應用中,如果你已經是稍有水平開發者,你就應該始終以PreparedStatement代替Statement.也就是說,在任何時候都不要使用Statement。
以下的代碼段(其中 con 是 Connection 對象)創建包含帶兩個 IN 參數佔位符的 SQL 語句的 PreparedStatement 對象:
PreparedStatement pstmt = con.prepareStatement("UPDATE table4 SET m = ? WHERE x = ?")
在執行 PreparedStatement 對象之前,必須設置每個 ? 參數的值。這可通過調用 setXXX 方法來完成,其中 XXX 是與該參數相應的類型。例如,如果參數具有Java 類型 long,則使用的方法就是 setLong。setXXX 方法的第一個參數是要設置的參數的序數位置,第二個參數是設置給該參數的值。例如,以下代碼將第一個參數設爲 123456789,第二個參數設爲 100000000:
pstmt.setLong(1, 123456789);
pstmt.setLong(2, 100000000);
使用PreparedStatement來實現增刪該查的源碼,可反覆推敲:
package com.bjsxt.bbs2009.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import com.bjsxt.bbs2009.model.Category;
import com.bjsxt.bbs2009.util.DB;
public class CategoryService {
public void add(Category category) {
Connection conn = DB.createConnectionion();
String sql = "insert into _category values (null, ?, ?)";
PreparedStatement ps = DB.prepare(conn, sql);
try {
ps.setString(1, "JavaSE");
ps.setString(2, "JavaSE Description");
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
DB.close(ps);
DB.close(conn);
}
public void update(Category c) {
Connection conn = DB.createConnectionion();
String sql = "update _category set name = ? and descrition = ? where id = ?";
PreparedStatement ps = DB.prepare(conn, sql);
try {
ps.setString(1, c.getName());
ps.setString(2, c.getDescription());
ps.setInt(3, c.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
DB.close(ps);
DB.close(conn);
}
public void delete(Category c) {
deleteById(c.getId());
}
public void deleteById(int id) {
Connection conn = DB.createConnectionion();
String sql = "delete from _category where id = ?";
PreparedStatement ps = DB.prepare(conn, sql);
try {
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
DB.close(ps);
DB.close(conn);
}
public Set<Category> query() {
Connection conn = DB.createConnectionion();
String sql = "select id, name, description from _category";
PreparedStatement ps = DB.prepare(conn, sql);
ResultSet rs = null;
Set<Category> categories = new HashSet<Category>();
try {
rs = ps.executeQuery();
Category c = null;
while(rs.next()) {
c = new Category();
c.setId(rs.getInt("id"));
c.setName(rs.getString("name"));
c.setDescription(rs.getString("description"));
categories.add(c);
}
} catch (SQLException e) {
e.printStackTrace();
}
DB.close(ps);
DB.close(conn);
return categories;
}
}