JDBC Steps

Java JDBC is a Java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database.

We can use JDBC API to access tabular data stored into any relational database.

We can use JDBC API to handle database using Java program and can perform following activities:

  1. Connect to the database
  2. Execute queries and update statements to the database
  3. Retrieve the result received from the database.

Steps

firstly we need to establish a connection between database and java file with the help of various types of APIs, interfaces and methods. We are using MySQL database.

Connection: This interface specifies connection with specific databases like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of this interface.

Class.forName(String driver): It loads the driver.

DriverManager: This class 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 is having three arguments:

url: - Database url where stored or created your database

username: - User name of MySQL

password: -Password of MySQL

Example:-

<%@ page import="java.sql.*" %>

<%@ page import="java.io.*" %>

<%

try {

/* Create string of connection url within specified format with machine name,

port number and database name. Here machine name id localhost and

database name is usermaster. */

String connectionURL = "jdbc:mysql://localhost:3306/usermaster";

// declare a connection by using Connection interface

Connection connection = null;

// Load JBBC driver "com.mysql.jdbc.Driver"

Class.forName("com.mysql.jdbc.Driver").newInstance();

/* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */

connection = DriverManager.getConnection(connectionURL, "root", "rootroot");

// check weather connection is established or not by isClosed() method

if(!connection.isClosed())

%>

<font size="+3" color="green"></b>

<%

out.println("Successfully connected to " + "MySQL server using TCP/IP...");

connection.close();

}

catch(Exception ex){

%>

</font>

<font size="+3" color="red"></b>

<%

out.println("Unable to connect to database.");

}

%>