我正在运行一个Spring MVC应用程序,该应用程序由我使用JDBC访问的MySQL数据库支持。我一直在使用相同的代码,并且从未真正看过我是否正确使用它(正确使用连接池等)。错误地使用JDBC连接池
我知道有JDBCTemplate那里,我已经考虑过使用它,但如果唯一的好处是我只是不必写样板代码,那么我不太相信我应该使用它。事实上,我更喜欢我的代码在JDBCTemplate代码上的可读性。
下面是我的DAO中的代码,出于某种原因,我觉得我没有正确使用ConnectionPooling。
public Agent get(Integer id){
ConnectionPool pool = new ConnectionPool();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
try{
String query = "SELECT * FROM agent where id= ?";
ps = connection.prepareStatement(query);
ps.setInt(1,id);
ResultSet rs = ps.executeQuery();
Agent agent = null;
if(rs.next()){
agent = new Agent();
agent.setFirstName(rs.getString(1));
agent.setLastName(rs.getString(2));
agent.setStreet(rs.getString(3));
agent.setCity(rs.getString(4));
agent.setZip(rs.getString(5));
agent.setState(rs.getString(6));
agent.setUsername(rs.getString(7));
agent.setPassword(rs.getString(8));
agent.setId(rs.getInt(9));
agent.setEmail(rs.getString(10));
}
return agent;
}
catch(SQLException e)
{
e.printStackTrace();
return null;
}
finally{
ConnectionUtility utility = new ConnectionUtility();
utility.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
上面的代码是什么,我担心的绝大多数是不正确的,但我有也可以有助于不良做法/不当代码的一些实用程序类。
以下是我的ConnectionUtility类。
public class ConnectionUtility{
public static void closeStatement(Statement s){
try{
if(s != null){
s.close();
}
}
catch(SQLException e){
e.printStackTrace();
}
}
public void closePreparedStatement(Statement ps){
try{
if(ps != null){
ps.close();
}
}
catch(SQLException e){
e.printStackTrace();
}
}
public static void closeResultSet(ResultSet rs){
try{
if(rs != null){
rs.close();
}
}
catch(SQLException e){
}
}
}
这是我连接池类,
public class ConnectionPool {
private static ConnectionPool pool = null;
public ConnectionPool(){
}
public static ConnectionPool getInstance(){
if(pool == null){
pool = new ConnectionPool();
}
return pool;
}
@SuppressWarnings("static-access")
public Connection getConnection(){
try{
return ConnectionFactory.getInstance().getConnection();
}
catch(SQLException e){
e.printStackTrace();
return null;
}
}
public void freeConnection(Connection c){
try{
c.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
再次,我觉得我真的很喜欢使用所有这些类的错误,即使一切正常,但没有已经投入生产中的测试。
我更喜欢呆在JDBC中,所以请不要将切换到另一个。
Jeez,安顿下来。问题是关于如何改进他的代码。您的评论没有帮助。 – 2010-10-20 00:35:42
我正在改进他的代码。使用Spring将是一个巨大的进步。这比你知道的更有帮助。 – duffymo 2010-10-20 00:53:55
建议Spring有帮助。告诉他他的代码是可怕的,你永远不会和他一起工作,并且他不应该获得他的学位不是。 – 2010-10-20 00:58:10