I would say that your code is an example of many worst practices. Let me figure out the ways:
- Your Connection class is a bad abstraction that contains nothing but java.sql.Connection.
- If you use your class, you can never use the connection pool.
- You firmly connect your driver class, the URL of your connection, etc. You cannot change it without editing and recompiling. The best solution would be to externalize such things.
- Printing error messages in catch blocks has much less information than providing the entire stack trace.
- Your code hurts me. It does not comply with Sun Java coding standards.
- Your
retrieveData method is completely useless. What will you do with all these print statements? Wouldn't it be better to load them into a data structure or object so that the rest of your code can use this information? - This is
rowsAffected - "influences" is a verb, "effect" is a noun. Another variable that is not useful.
You're wrong. Rethink it.
I think you will find this code more useful.
package persistence; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DatabaseUtils { public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException { Class.forName(driver); if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0)) { return DriverManager.getConnection(url); } else { return DriverManager.getConnection(url, username, password); } } public static void close(Connection connection) { try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void close(Statement st) { try { if (st != null) { st.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void close(ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void rollback(Connection connection) { try { if (connection != null) { connection.rollback(); } } catch (SQLException e) { e.printStackTrace(); } } public static List<Map<String, Object>> map(ResultSet rs) throws SQLException { List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); try { if (rs != null) { ResultSetMetaData meta = rs.getMetaData(); int numColumns = meta.getColumnCount(); while (rs.next()) { Map<String, Object> row = new HashMap<String, Object>(); for (int i = 1; i <= numColumns; ++i) { String name = meta.getColumnName(i); Object value = rs.getObject(i); row.put(name, value); } results.add(row); } } } finally { close(rs); } return results; } }
source share