×

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java.

5 Steps to Connect to the Database in Java

  • Load the driver (or) Register the driver class
  • Establish a connection (or) Create a connection
  • Creating statement
  • Executing queries & obtain the result
  • Closing the connection

Register the Driver Class:

Software that contains classes and interfaces created using the JDBC API is referred to as a database driver.

Given the variety of drivers on the market, we need first to specify the driver that will be used in a Java programme to communicate with the database server.

The driver class is registered using the forName() function of the Class. The driver class is dynamically loaded using this technique.            

Syntax:

public static void forName(String className)throws ClassNotFoundException

Example:

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

In order to connect to the database, a programmer must identify the database driver he will be using. There are four ways to register a driver.

  • The driver can be registered by creating an object that belongs to the driver class of the driver programme. for instance
com.mysql.jdbc.Driver obj = new com.mysql.jdbc.Driver ();
  • The driver class object should be sent to the second method of registering a driver. The DriverManager class's registerDriver() function. As an illustration,
DriverManager.registerDriver ( new com.mysql.jdbc.Driver () );
  • The third way to register the driver is to send the driver class name directly to forName() method,as:
Class.forName(“com.mysql.jdbc.Driver”);

Create the Connection Object

To connect to the database, utilise the getConnection() function of the DriverManager class.

Syntax:


1) public static Connection getConnection(String URL)throws SQLException




2) public static Connection getConnection(String URL, String name, String password)
throws SQLException

Connection:

c=DriverManager.getConnection("jdbc:mysql:thin:@localhost:1521:xe","system","password"); 

Three items are necessary to connect to a database:

  • URL: The database's URL is a protocol to connect to the database is represented by the URL (Uniform Resource Locator). In a nutshell, it finds the database on the network.
  • Username: Each user will be granted a username to connect to a database, which is typically assigned by the database administrator.
  • Password: This is the password that the database administrator assigned to the user to log in to the database.

Create the Statement Object:

Statements are created using the Connection interface's createStatement() function. Executing database queries is the responsibility of the object of the statement.

Syntax:

public Statement createStatement() throws SQLException

Once created, the connection is used to transmit SQL commands to the database.

For transmitting SQL statements to databases, the java.sql package provides three interfaces:

Specifically, the Statement interface and its two sub-interfaces, PreparedStatement and CallableStatement.

The objects of these three sentences are returned by three methods of the Connection object.

When sending a SQL statement to the database without any arguments, a Statement object is utilised. By utilising the Connection Object's createStatement(String query) method, its instances are returned.

Statement object Example:

Statement stmt=con.createStatement();

PreparedStatement object:

Precompiled statements can be sent to databases with or without IN arguments using a PreparedStatement object. The insert SQL command is typically used to add rows of data to databases.

An insert SQL statement is created and submitted to the database for each insertion. The identical expression is constructed n times if there are n rows that need to be added. It takes up a lot of time. Because of this, we employ PreparedStatement which has already been precompiled. Only the values that need to be added in this situation are sent repeatedly to the database.

Syntax:

PreparedStatement ps=con.prepareStatement(String query);

CallableStatement Object:

A CallableStatement object is used to invoke functions and stored procedures running on a database server and deliver the results to the client.

A stored procedure is a collection of statements that are saved, executed, and provided to the client by a database server.

Syntax:

CallableStatement cs=con.prepareCall(String query);

Execute the Query

The Statement interface's executeQuery() function is used to run database queries.

The object of ResultSet that can be used to get all of a table's records is returned by this method. The results (rows) of running a SQL command on a database are contained in an object called a "ResultSet."

Syntax:

public ResultSet executeQuery(String sql)throws SQLException

Example:

ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
    System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

Close the Connection Object:

The Connection interface's close() function is used to terminate the connection. Statement and ResultSet will be closed automatically by closing the connection object. 

Syntax:

public void close()throws SQLException

Example:

con.close();

Program:

import java.io.*;
import java.sql.*;
public class DBC {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/emp";
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) 
{
Connection c = null;
Statement s = null;
try{
//STEP 2: Register JDBC driver 
Class.forName("com.mysql.cj.jdbc.Driver");
//STEP 3: Establish a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,"root","");
//STEP 4: Creating a Statement
System.out.println("Creating statement...");
s = c.createStatement();
String sql;
sql = "SELECT id,name, age FROM Students";
ResultSet rs = s.executeQuery(sql);
//STEP 5: Executing Queries
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("Name");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", Name: " + name);
}
//STEP 6: Closing the Connection
rs.close();
s.close();
c.close();
}catch(SQLException se){
//Exception Handling for JDBC
se.printStackTrace();
}catch(Exception e){
//Exception Handling for Class.forName
e.printStackTrace();
}finally{
System.out.println("THE END");
}//finally block
}//end main
}

Related Topics

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.