Program to show Connectivity using JDBC

Java Database Connectivity or in short JDBC is a technology that enables the java program to manipulate data stored into the database. Here is the complete tutorial on JDBC technology.

JDBC: JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems.

Product Components of JDBC: JDBC is consists of four Components The JDBC API, JDBC Driver Manager, The JDBC Test Suite and JDBC-ODBC Bridge.

Layers of the JDBC Architecture

Example: This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected from database".

import java.sql.*;
import java.io.*;
public class MysqlConnect
{
public static void main(String[] args)
{
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Understand Code
Connection: This is an interface in java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver): This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that matches class with given string.

DriverManager: It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password): This method establishes a connection to specified database url. It takes three string types of arguments like:

url: - Database url where stored or created your database
userName: - User name of MySQL
password: -Password of MySQL

con.close(): This method is used for disconnecting the connection. It frees all the resources occupied by the database.

printStackTrace(): The method is used to show error messages. If the connection is not established then exception is thrown and print the message.

See also
JDBC Driver and Its Types

No comments:

Google Search