Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Mysql-Connector- Java vs Spring-Jdbc

As far as I know we use Mysql-connector jar for connecting java application to the database. I am following a spring tutorial and both the above mentioned things have been added via maven. What is the difference between both?

like image 833
no one Avatar asked Oct 23 '25 21:10

no one


1 Answers

MySQL Connector is a driver that allows Java to talk to MySQL.

Spring JDBC is a library that makes it easier to write JDBC code. JdbcTemplate is particularly useful.

Before JdbcTemplate:

Connection connection = null;
Statement statement = null;
ResultSet rs = null;
int count;

try {
  connection = dataSource.getConnection();
  statement = connection.createStatement();
  rs = statement.executeQuery("select count(*) from foo");
  if(rs.next()) {
    count = rs.getInt(0);
  }
} catch (SQLException exp) {
  throw new RuntimeException(exp);
} finally {
  if(connection != null) {
    try { connection.close(); } catch (SQLException exp) {}
  }
  if(statement != null) {
    try { statement.close(); } catch (SQLException exp) {}
  }
  if(rs != null) {
    try { rs.close(); } catch (SQLException exp) {}
  }
}

After JdbcTemplate:

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForObject("select count(*) from foo", Integer.class);

See how one way sucks much less?

like image 126
Neil McGuigan Avatar answered Oct 25 '25 15:10

Neil McGuigan