package com.michael.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.michael.dao.LinkDao; import com.michael.util.ConnectionUtil; import com.michael.util.SQLConstants; import com.michael.vo.Link; public class LinkDaoImpl implements LinkDao,SQLConstants{ public void add(Link l) { Connection conn = new ConnectionUtil().openConnection(); try { PreparedStatement pstmt = conn.prepareStatement(ADD_LINK_SQL); pstmt.setString(1, l.getName()); pstmt.setString(2, l.getUrl()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void delete(String[] ids) { Connection conn = new ConnectionUtil().openConnection(); try { PreparedStatement pstmt = conn.prepareStatement(DELETE_LINK_SQL); if(ids!=null&&ids.length>0) for(int i=0;i<ids.length;i++){ pstmt.setInt(1, Integer.parseInt(ids[i])); pstmt.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); }finally{ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public Link get(int id) { Connection conn = new ConnectionUtil().openConnection(); try { PreparedStatement pstmt = conn.prepareStatement(GET_LINK_SQL); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); if(rs.next()){ //int id = rs.getInt(1); String name = rs.getString(2); String url = rs.getString(3); Link l = new Link(); l.setId(id); l.setName(name); l.setUrl(url); return l; } } catch (SQLException e) { e.printStackTrace(); }finally{ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return null; } public List list() { Connection conn = new ConnectionUtil().openConnection(); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(QUERY_LINK_SQL); List list = new ArrayList(); while(rs.next()){ int id = rs.getInt(1); String name = rs.getString(2); String url = rs.getString(3); Link l = new Link(); l.setId(id); l.setName(name); l.setUrl(url); list.add(l); } return list; } catch (SQLException e) { e.printStackTrace(); }finally{ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return null; } public void update(Link l) { Connection conn = new ConnectionUtil().openConnection(); try { PreparedStatement pstmt = conn.prepareStatement(UPDATE_LINK_SQL); pstmt.setString(1, l.getName()); pstmt.setString(2, l.getUrl()); pstmt.setInt(3, l.getId()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
JDBC实现的增删改查
猜你喜欢
转载自chenzheng8975.iteye.com/blog/1861514
今日推荐
周排行