JDBC lightweight connection
Is there a library that will simplify the task of connecting to a server with JDBC? Something that can take a string of type mysql://username:password@host/db
similar to what it PHP MDB2
does as in here .
I am not interested in any ORM or complex library such as Spring
since I don't even do this from the language Java
(but still on the JVM).
0
source to share
1 answer
Here is an example using JdbcTemplate from Spring.
static void jdbcTemplateExample() {
DataSource ds = DataSourceBuilder
.create()
.username(username)
.password(password)
.url(url)
.build();
JdbcTemplate jt = new JdbcTemplate(ds);
List<Object> results = jt.query("SELECT * FROM table", (ResultSet rs, int rowNum) -> {
//Create whatever Object you want with the resultSet.
//Will convert to Map as example.
Map results = new HashMap<>();
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; ++i) {
results.put(md.getColumnName(i), rs.getObject(i));
}
return results;
});
//use the results
}
0
source to share