Refactor
:my
=>
'code'
Codes
Refactorings
Popular
Best
Submit
Spam
Account
Logout
Login
JavaScript doesn't seem to be activated, expect things to be ugly and sloppy!
Learn How to Create Your Own Programming Language
createyourproglang.com
Recent
FILE HOSTS PREMIUM ACCOUNT
ALL FILE HOST PREMIUM ACCOUNTS
Zynga Slingo Trainer v5.12
iTunes Gift Card Generator V3.1 2012
Diablo 3 GOLD Coins FREE
Working PS3 Jailbreak 3.65 And 3.66
ExtaBit Premium Accounts and Cookies
Steam Wallet Hack - Money Adder & Hack v3
Empires & Allies Hack Cheat Trainer v5.4.1
Eve Onnline 60 Days Time Card Generator v2
Popular
XBOX POINTS GENERATOR - MICROSOFT POINTS GENERATOR v1.2012
11 may 2012 premium uploading accounts 100% working
Free Microsoft Points
Free Microsoft Points - Microsoft Points Generator - Xbox Live Codes 2012
Car Town Free Blue Points Hack
Free CarTown Blue Points Generator and CarTown Templates
Better way to get content via jQuery $.get()
Free Microsoft Points
Simple Days Purger
Sharecash Downloader Bypass Surveys New 05/2012
Pastable version of
Closing database connections properly
<pre class='prettyprint' language='java'>/** * Get the article destined for the front page * * @return a linked list of the articles */ public LinkedList<ArticleBean> getFrontpageArticles() { DatabaseBean dbaBean = new DatabaseBean(); LinkedList<ArticleBean> listOfBeans = new LinkedList<ArticleBean>(); try { dbaBean.setPrepStmt(dbaBean.getConn().prepareStatement( "SELECT id, title, url, author, date_time, article_text " + "FROM articles " + "ORDER BY id desc " + "LIMIT 5;")); } catch (SQLException SQLEx) { logger.fatal("Problem with the SQL in the ArticleProcessBean.getFrontpageArticles() function"); logger.fatal(SQLEx); } ResultSet result = dbaBean.executeQuery(); try { while (result.next()) { // Make a new ArticleBeanTest that represents one article ArticleBean articleBean = new ArticleBean(); // Set the properties of the bean articleBean.setArticleID(result.getString("id")); articleBean.setAuthor(result.getString("author")); articleBean.setTitle(result.getString("title")); articleBean.setURL(result.getString("url")); articleBean.setArticleText(result.getString("article_text")); articleBean.setDateTime(result.getTimestamp("date_time")); // Process this articles tags try { TagProcessBean tagProcessBean = new TagProcessBean(); tagProcessBean.setArticleID("" + result.getInt("id")); // Set the user in the TagProcessBean *cast to String* articleBean.setTags(tagProcessBean.getArticleTags()); // Assign the results to the bean } catch (SQLException SQLEx) { logger.warn(SQLEx); } listOfBeans.add(articleBean); //Add the now populated bean to the list to be returned for display } } catch (SQLException SQLEx) { logger.warn("You had an error mapping objects in ArticleProcessBean.getFrontpageArticles()"); logger.warn(SQLEx); } try { result.close(); dbaBean.close(); } catch (SQLException SQLEx) { logger.warn("There was an error closing the resultset and the database connection."); logger.warn(SQLEx); } return listOfBeans; }</pre> <pre class='prettyprint' language='java'>package com.mysite.utilities; import org.apache.log4j.Logger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.*; /** * Contains a collection of database access related functions. * Including update and execute. */ public class DatabaseBean { private static final Logger logger = Logger.getLogger(DatabaseBean.class); private Connection conn; private PreparedStatement prepStmt; /** * Zero argument constructor * Setup generic databse connection in here to avoid redundancy * The connection details are in /META-INF/context.xml */ public DatabaseBean() { try { InitialContext initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/mysite"); conn = ds.getConnection(); } catch (SQLException SQLEx) { logger.fatal("There was a problem with the database connection."); logger.fatal(SQLEx); logger.fatal(SQLEx.getCause()); } catch (NamingException nameEx) { logger.fatal("There was a naming exception"); logger.fatal(nameEx); logger.fatal(nameEx.getCause()); } } /** * Execute a query. Do not use for statements (update delete insert etc). * * @return A ResultSet of the execute query. A set of size zero if no results were returned. It is never null. * @see #executeUpdate() for running update, insert delete etc. */ public ResultSet executeQuery() { // This is the returned query from the database. ResultSet result = null; try { result = prepStmt.executeQuery(); logger.debug(prepStmt.toString()); } catch (SQLException SQLEx) { logger.fatal("There was an error running a query"); logger.fatal(SQLEx); } // Return the result set to the caller and finish this database call return result; } /** * Close the open database connection. This method is called from the process beans as the connections cant be closed before the resultset is returned<br /> * <p/> * This closes both the statment and the connection */ public void close() { try { prepStmt.close(); prepStmt = null; conn.close(); conn = null; } catch (SQLException SQLEx) { logger.warn("There was an error closing the database connection."); } } public Connection getConn() { return conn; } public PreparedStatement getPrepStmt() { return prepStmt; } public void setPrepStmt(PreparedStatement prepStmt) { this.prepStmt = prepStmt; } }</pre> <pre class='prettyprint' language='java'><Resource name="jdbc/mysite" auth="Container" type="javax.sql.DataSource" username="user" password="pass" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mysite?autoReconnect=true" maxActive="10" maxIdle="0" maxWait="5000" removeAbandoned="true" removeAbandonedTimeout="15" validationQuery="SELECT 1;" /></pre> <a href="http://www.refactormycode.com/codes/409-clsing-database-connections-properly" style="color:#fff" title="As seen on RefactorMyCode.com"><img alt="Small_logo" src="http://www.refactormycode.com/images/small_logo.gif" style="border:0" /></a>