This class handles the JDBC connection to the MySQL database and how to create an array associative in Java from a database Resultset.
Mapping a resultset into a list of Maps: One Map per database row by setting the Map key name as the database field name by getting the ResultSetMetaData properties and setting the Map value as an object
A list object that can be easily iterated through.
/**
* JDBC connection to MySQL database and map the resultset (create an array associative).
*/
public class DbObject
{
public static Connection getDbConnection()
{
Connection cnn=null;
String DB_SERVER="yourserver";
String DB_NAME="yourdbname";
String DB_LOGIN="yourdblogin";
String DB_PASSWORD="yoursdbpassword";
try
{
cnn = DriverManager.getConnection("jdbc:mysql://"+DB_SERVER+"/"+DB_NAME+"?" +
"user="+DB_LOGIN+"&password="+DB_PASSWORD);
}
catch (SQLException ex)
{
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
return cnn;
}
///////////////
/// HELPERS ///
///////////////
/**
* Helper method that converts a ResultSet into a list of maps, one per row
* @param query ResultSet
* @return list of maps, one per row, with column name as the key
* @throws SQLException if the connection fails
*/
public static final List toList(ResultSet rs) throws SQLException
{
List wantedColumnNames = getColumnNames(rs);
return toList(rs, wantedColumnNames);
}
/**
* Helper method that maps a ResultSet into a list of maps, one per row
* @param query ResultSet
* @param list of columns names to include in the result map
* @return list of maps, one per column row, with column names as keys
* @throws SQLException if the connection fails
*/
public static final List toList(ResultSet rs, List wantedColumnNames) throws SQLException
{
List rows = new ArrayList();
int numWantedColumns = wantedColumnNames.size();
while (rs.next())
{
Map row = new TreeMap();
for (int i = 0; i < numWantedColumns; ++i)
{
String columnName = (String)wantedColumnNames.get(i);
Object value = rs.getObject(columnName);
row.put(columnName, value);
}
rows.add(row);
}
return rows;
}
/**
* Return all column names as a list of strings
* @param database query result set
* @return list of column name strings
* @throws SQLException if the query fails
*/
public static final List getColumnNames(ResultSet rs) throws SQLException
{
List columnNames = new ArrayList();
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
for (int i = 1; i <= numColumns; ++i)
{
columnNames.add(meta.getColumnName(i));
}
return columnNames;
}
/**
* Closing methods are to close Statements, ResulSet and Connections in this order
* please call these methods inside a catch finally block
*
* @param cnn
*/
public static void closeConnection(final Connection cnn)
{
if (cnn != null)
{
try
{
cnn.close();
}
catch (SQLException ex)
{
//log errors
}
}
}
/**
* Closing a Statement
*
* @param stmt
*/
public static void closeStatement(final Statement stmt){
if (stmt != null)
{
try
{
stmt.close();
}
catch (SQLException ex){
//log errors
}
}
}
/**
* Closing a ResultSet
*
* @param rs
*/
public static void closeResultSet(final ResultSet rs)
{
if (rs != null)
{
try
{
rs.close();
}
catch (SQLException ex)
{
// log errors
}
}
}
}
Iterating through resultset
Reading DATETIME fields from a MySQL database and casting Timestamp to Date
// Some code ..
String sql="SELECT product_id,name,update_date FROM product";
rs = stmt.executeQuery(sql);
List list=DbObject.toList(rs);
Iterator i = list.iterator();
while(i.hasNext())
{
Map map = (Map) i.next();
Integer product_id = new Integer(((Number) map.get("product_id")).intValue());
String name=(String)map.get("name");
// Date Type, set 1970 as default value
java.util.Date d = new java.util.Date(24L*60L*60L*1000L);
Timestamp st=(Timestamp) map.get("update_date");
if(st!=null)
{
d = new java.util.Date(st.getTime());
}
System.out.println("product_id :"+product_id+" name: "+name+" date: "+d);
}
// Some code