no one
no one

Reputation: 477

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?

Upvotes: 4

Views: 2620

Answers (1)

Neil McGuigan
Neil McGuigan

Reputation: 48287

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?

Upvotes: 5

Related Questions