Skip to content

Instantly share code, notes, and snippets.

@jinto
Created September 19, 2018 16:32
Show Gist options
  • Save jinto/54512d2927d06529d052a3477859d2dc to your computer and use it in GitHub Desktop.
Save jinto/54512d2927d06529d052a3477859d2dc to your computer and use it in GitHub Desktop.
Java8 lambda and JDBC for compact code.
/**
* With java8 lambda you can use JDBC like
*
* return select("SELECT fields from table_name where id=?", (params)-> {
* params.add("user_id");
* });
*
*/
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.sql.*;
public class LambdaJDBC {
public static HashMap<String, String> calling_lambda_jdbc() throws ApsException {
return select("SELECT fields from table_name where id=?", (params)-> {
params.add("user_id");
});
}
public static HashMap<String, String> select(String query, ParamProcessor processor) throws ApsException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rset = null;
HashMap<String, String> map = null;
try {
conn = DbSrc.getConnection(); // external data pool
stmt = conn.prepareStatement(query);
List<String> params = new ArrayList<String>();
processor.process(params); // calling function parameter.
int index = 1;
for(String s : params) {
stmt.setString(index, s);
index++;
}
rset = stmt.executeQuery();
ResultSetMetaData md = rset.getMetaData();
int columns = md.getColumnCount();
if (rset.next()) {
map = new HashMap<String, String>(columns);
for(int i=1; i<=columns; ++i)
map.put(md.getColumnName(i),rset.getString(i));
}
return map;
} catch (SQLException e) {
throw new ApsQueryException(e.toString());
} finally {
try { if (rset != null) rset.close(); } catch(Exception e) { }
try { if (stmt != null) stmt.close(); } catch(Exception e) { }
try { if (conn != null) conn.close(); } catch(Exception e) { }
}
}
}
// normal jdbc code
// starting with getconnection, execute
public class NormalJDBC {
public static Dict select_query(String userid) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rset = null;
Dict map = null;
try {
conn = DataSrc.getConnection();
stmt = conn.prepareStatement("SELECT * FROM TABLE_NAME WHERE TYP in (?, ?, ?) and ID = ?");
stmt.setString(1, "1");
stmt.setString(2, "2");
stmt.setString(3, userid);
rset = stmt.executeQuery();
ResultSetMetaData md = rset.getMetaData();
int columns = md.getColumnCount();
if (rset.next()) {
map = new Dict(columns);
for(int i=1; i<=columns; ++i)
map.put(md.getColumnName(i),rset.getString(i));
}
return map;
} finally {
try { if (rset != null) rset.close(); } catch(Exception e) { }
try { if (stmt != null) stmt.close(); } catch(Exception e) { }
try { if (conn != null) conn.close(); } catch(Exception e) { }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment