package com.ww.bbs.util; import java.sql.*; public class connDB { private Connection conn = null; private Statement stmt = null; private ResultSet rs = null; private PreparedStatement ps =null; /** * * 获取数据库连接 * * @return */ public Connection getConn() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager .getConnection("jdbc:mysql://localhost/bbs?user=root&password=root"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } /** * * 执行查询语句sql * * @param sql * * @return */ public ResultSet getResultSet(String sql) { try { if (conn == null || conn.isClosed()) conn = this.getConn(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; } /** * * 更新sql语句 * * @param sql * * @return 整数,更新的条数 */ public int excuteUpdate(String sql) { int result = 0; try { if (conn == null || conn.isClosed()) conn = this.getConn(); result = conn.createStatement().executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * PreparedStatement的应用 * * @param sql * @return 整数,更新的条数 */ public PreparedStatement getPreparedStatement(String sql) { try { if (conn == null || conn.isClosed()) conn = this.getConn(); ps= conn.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return ps; } /** * * 关闭连接 */ public void closeConn() { try { if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } if( ps != null){ ps.close(); ps = null; } } catch (SQLException e) { System.out.println("关闭数据库出错!"); } } }