Sunday, September 11, 2011

How to create a JDBC Connection in Java?

JDBC (Java DataBase Connectivity) is an API for the Java programming language through which the databse can be accessed using methods for querying and updating data.
Here is the sample code -

import java.sql.*;

public class ConnectionInfo {

    public Connection getConnection() {
        Connection conn = null;
        // the below properties should be read from a properties file based on the Database used
        String url = "jdbc:mysql://localhost:3306/"; // url = jdbc:[subprotocol]://[hostname]:[portnumber]/
        String dbName = "jdbctutorial"; // database name
        String driver = "com.mysql.jdbc.Driver"; //Driver class name
        String username = "root"; // username
        String password = "root"; // password
        try {
          Class.forName(driver); // Dynamic loading based on database used.
          conn = DriverManager.getConnection(url + dbName, username, password);
          System.out.println("Connection Established");
        } catch (SQLException e) {
          e.printStackTrace();
        } finally {
            return conn;
        }
    }

    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

No comments:

Post a Comment