×

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

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.