日期:2014-05-20 浏览次数:20957 次
/** * 获取数据库连接 * @return 数据库连接 */ public static Connection createConn() { Connection conn = null; try { Class.forName(DBData.DRIVER); conn = DriverManager.getConnection(DBData.getURLForMySQL(), DBData.USER, DBData.PASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); //JOptionPane.showMessageDialog(Source.getMainWindow(), "创建数据库连接失败,请检查服务器运行状态."); //return createConn(); } return conn; } /** * 获取数据库Statement * @param conn 数据库连接 * @return 数据库stmt */ public static Statement createStmt(Connection conn) { Statement stmt = null; try { stmt = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } return stmt; } /** * 获取数据库PreparedStatement * @param conn 连接 * @param sql sql语句 * @return PreparedStatement */ public static PreparedStatement prepare(Connection conn, String sql) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return ps; } /** * 关闭Connection * @param conn 数据库连接 */ public static void close(Connection conn) { try { conn.close(); conn = null; } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭Statement * @param stmt Statement */ public static void close(Statement stmt) { try { stmt.close(); stmt.cancel(); stmt = null; } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭PreparedStatement * @param pstmt PreparedStatement */ public static void close(PreparedStatement pstmt) { try { pstmt.close(); pstmt.cancel(); pstmt = null; } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭结果集 * @param rs 查询结果集 */ public static void close(ResultSet rs) { try { rs.close(); rs = null; } catch (SQLException e) { e.printStackTrace(); } }
Connection connection = DB.createConn(); PreparedStatement pstmt = DB.prepare(connection, sql);//获取stmt ResultSet rs = null; try { pstmt.setString(1, XXXX); rs = pstmt.executeQuery(); while(rs.next()){ XXXXXX } } catch (SQLException e) { e.printStackTrace(); }finally{ DB.close(rs); DB.close(pstmt); DB.close(connection); }