public void closeStatement(Statement stmt){ try{ if(stmt!=null) stmt.close(); }catch(SQLException e){ e.printStackTrace(); } }
public void closeResult(ResultSet rs){ try { if(rs!=null) rs.close(); } catch (SQLException e1) { e1.printStackTrace(); } }
public void commitTrans(Connection conn){ try{ if(conn!=null) conn.commit(); } catch (SQLException e1) { e1.printStackTrace(); } }
public void rollbackTrans(Connection conn){ try{ if(conn!=null) conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } }
执行各种查询与插入数据库的核心代码:
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;
public abstract class BaseDAO { protected DbConnection dbconn; public BaseDAO(){ dbconn=new DbConnection(); } //执行增,删,改等操作,不返回结果集,返回影响记录的行数 public int updateBySql(String sql) throws Exception{ System.out.println(sql); Connection conn=null; Statement stmt=null; try { conn=dbconn.getConnection(); stmt=conn.createStatement(); return stmt.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return -1; }finally{ dbconn.closeStatement(stmt); dbconn.closeConnection(conn); } }
通过sql语句更新 public int updateBySql(String sql,IParamBinding bind) throws Exception{ Connection conn=null; PreparedStatement pstmt=null; try { conn=dbconn.getConnection(); pstmt=conn.prepareStatement(sql); bind.bindParam(pstmt);//参数绑定 return pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return -1; }finally{
//
dbconn.closeStatement(pstmt); dbconn.closeConnection(conn); } }
//执行多条不带参数的sql语句
public int[] executeBatch(String[] sqls) throws Exception{ Connection conn=null; Statement stmt=null; try { conn=dbconn.getConnection(); conn.setAutoCommit(false); stmt=conn.createStatement(); for(int i=0;i 通过sql语句查询 public List queryBySql(String sql,IRowMapper mapper) throws Exception{ System.out.println(sql); Connection conn=null; Statement stmt=null; ResultSet rs=null; List retList=new ArrayList(); try { conn=dbconn.getConnection(); stmt=conn.createStatement(); rs=stmt.executeQuery(sql); while(rs.next()){ Object obj=mapper.mappingRow(rs); } retList.add(obj); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ dbconn.closeResult(rs); dbconn.closeStatement(stmt); dbconn.closeConnection(conn); } return retList; 3.4图书管理系统的实现 1)系统管理员登陆到后台进行操作。 图3.1 系统管理员后台界面 2)系统管理员可以对个人信息进行修改 图3.2 个人信息界面 3)系统管理员可以对作者进行管理。 图3.3 管理作者界面 4)系统管理员可以添加、修改、删除图书。 图3.4 管理图书界面 5)系统管理员可以对普通用户和普通管理员进行管理。 图3.5 权限管理界面
相关推荐: