使用PreparedStatement实现增删该查

来源:互联网 发布:焦作青峰网络 编辑:程序博客网 时间:2024/05/21 14:07

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

 

 

 

 

0 0
原创粉丝点击