It’s very strange if you are still using JDBC in your project for database access because there are lot’s of powerful alternatives like hibernate and iBatis. But it is important to learn basics and it requires learning JDBC first.
In this post, I am giving an example of making a connection with database using MySQL Driver. Read more about types of JDBC drivers.
Handling a connection requires following steps:
1) Load the driver
2) Open database connection
3) Close database connection
Let’s follow above steps in code:
1) Load JDBC driver
The easiest way to do this is to use Class.forName() on the class that implements the java.sql.Driver interface. With MySQL Connector/J, the name of this class is com.mysql.jdbc.Driver. With this method, you could use an external configuration file to supply the driver class name and driver parameters to use when connecting to a database.
Class.forName("com.mysql.jdbc.Driver");
2) Open database connection
After the driver has been registered with the DriverManager, you can obtain a Connection instance that is connected to a particular database by calling DriverManager.getConnection():
Connection connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");
Once a Connection is established, it can be used to create Statement and PreparedStatement objects, as well as retrieve metadata about the database.
3) Close database connection
This step is as much important as opening a connection. Any connection left open is waste of resource and lead to various exceptions.
try { if(connection != null) connection.close(); System.out.println("Connection closed !!"); } catch (SQLException e) { e.printStackTrace(); }
Complete JDBC Connection Example
Let’s see the whole thing working in an example below:
package com.howtodoinjava.jdbc.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionDemo { public static void main(String[] argv) { System.out.println("-------- MySQL JDBC Connection Demo ------------"); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("MySQL JDBC Driver not found !!"); return; } System.out.println("MySQL JDBC Driver Registered!"); Connection connection = null; try { connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password"); System.out.println("SQL Connection to database established!"); } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); return; } finally { try { if(connection != null) connection.close(); System.out.println("Connection closed !!"); } catch (SQLException e) { e.printStackTrace(); } } } } Output: -------- MySQL JDBC Connection Demo ------------ MySQL JDBC Driver Registered! SQL Connection to database established! Connection closed !!
That’s all for this topic. Drop a comment if something needs more explanation.
Happy Learning !!
Leave a Reply