The Wayback Machine - https://web.archive.org/web/20241127005132/https://www.geeksforgeeks.org/how-to-create-a-database-connection/
Open In App

How to Create a Database Connection?

Last Updated : 15 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Java Database Connectivity is a standard API or we can say an application interface present between the Java programming language and the various databases like Oracle, SQL, PostgreSQL, MongoDB, etc. It basically connects the front end(for interacting with the users) with the backend for storing data entered by the users in the table details. JDBC or Java Database Connection creates a database by following the following steps:

  • Import the database
  • Load and register drivers
  • Create a connection
  • Create a statement
  • Execute the query
  • Process the results
  • Close the connection

Step 1: Import the database

Java consists of many packages that ease the need to hardcode every logic. It has an inbuilt package of SQL that is needed for JDBC connection. 

Syntax:

import java.sql* ;

Step 2: Load and register drivers

This is done by JVC(Java Virtual Machines) that loads certain driver files into secondary memory that are essential to the working of JDBC.

Syntax:

forName(com.mysql.jdbc.xyz);

class.forname() method is the most common approach to register drivers. It dynamically loads the driver file into the memory. 

Example:

try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e) {
   System.out.println("cant load driver class!");
   System.Exit(1);
}

Here, the oracle database is used. Now let us considered a random example of hotel database management systems. Now applying SQL commands over it naming this database as ‘sample’. Now suppose the user starts inserting tables inside it be named as “sample1” and “sample2“.


Java




// Connections class
  
// Importing all SQL classes
import java.sql.*;
  
public class connection{
 
// Object of Connection class
// initially assigned NULL
Connection con = null;
 
public static Connection connectDB()
{
    try
    {
         
        // Step 2: involve among 7 in Connection
        // class i.e Load and register drivers
 
        // 2(a) Loading drivers using forName() method
        // Here, the name of the database is mysql
        Class.forName("com.mysql.jdbc.Driver");
 
        // 2(b) Registering drivers using DriverManager
        Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/database",
            "root", "1234");
             
        // Root is the username, and
        // 1234 is the password
 
        // Here, the object of Connection class is return
        // which further used in main class
        return con;
    }
 
    // Here, the exceptions is handle by Catch block
    catch (SQLException | ClassNotFoundException e)
    {
         
        // Print the exceptions
        System.out.println(e);
 
        return null;
    }
}
}


Step 3: Create a connection

Creating a connection is accomplished by the getconnection() method of DriverManager class, it contains the database URL, username, and password as a parameter. 

Syntax:

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

Example:

String URL = "jdbc:oracle:thin:@amrood:1241:EMP";
String USERNAME = "geekygirl";
String PASSWORD = "geekss"
Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

Here, 

The database URL looks like- jdbc:oracle:thin:@amrood:1221:EMP
The username be-“geekygirl”
The passwords be-“geekss”

Step 4: Create a statement

Query statement is created to interact with the database by following the proper syntax. Before writing the query, we must connect the database using connect() method. For example:

conn = connection.connectDB();
String sql = "select * from customer";

This statement basically shows the contents of the customers’ table. We can also create a statement using the createStatement() method of the Connection interface. Here, the object of the statement is mainly responsible to execute queries.

Syntax:

public Statement createStatement()throws SQLException 

Example:

Statement s = conn.createStatement();

Step 5: Execute the query

For executing the query (written above), we need to convert the query in JDBC readable format, for that we use the preparedstatement() function and for executing the converted query, we use the executequery() function of the Statement interface. It returns the object of “rs” which is used to find all the table records.

Syntax:

public rs executeQuery(String sql)throws SQLException  

Example:

p = conn.prepareStatement(sql);
rs = p.executeQuery();

Step 6: Process the results

Now we check if rs.next() method is not null, then we display the details of that particular customer present in the “customer” table.next() function basically checks if there’s any record that satisfies the query, if no record satisfies the condition, then it returns null. Below is the sample code: 

while (rs.next())
{  
    int id = rs.getInt("cusid");
    String name = rs.getString("cusname");
    String email = rs.getString("email");
    System.out.println(id + "\t\t" + name + 
                            "\t\t" + email);
}

Step 7: Close the connection

After all the operations are performed it’s necessary to close the JDBC connection after the database session is no longer needed. If not explicitly done, then the java garbage collector does the job for us. However being a good programmer, let us learn how to close the connection of JDBC. So to close the JDBC connection close() method is used, this method close all the JDBC connection. 

Syntax:

public void close()throws SQLException  

Example:

conn.close();

Sample code is illustrated above:

Java




// Importing SQL libraries to create database
import java.sql.*;
   
class GFG{
   
// Step 1: Main driver method
public static void main(String[] args)
{
     
    // Step 2: Creating connection using
    // Connection type and inbuilt function
    Connection con = null;
    PreparedStatement p = null;
    ResultSet rs = null;
 
    con = connection.connectDB();
 
    // Here, try block is used to catch exceptions
    try
    {
         
        // Here, the SQL command is used to store
        // String datatype
        String sql = "select * from customer";
        p = con.prepareStatement(sql);
        rs = p.executeQuery();
 
        // Here, print the ID, name, email
        // of the customers
        System.out.println("id\t\tname\t\temail");
 
        // Check condition
        while (rs.next())
        {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String email = rs.getString("email");
            System.out.println(id + "\t\t" + name +
                                    "\t\t" + email);
        }
    }
 
    // Catch block is used for exception
    catch (SQLException e)
    {
         
        // Print exception pop-up on the screen
        System.out.println(e);
    }
}
}


Output:



Previous Article
Next Article

Similar Reads

SQL USE Database Statement
SQL(Structured Query Language) is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. It is flexible and user-friendly. In SQL, to interact with the database, the users have to type queries that have certain syntax, and use command is one of them. The use command is
2 min read
Querying Data from a Database using fetchone() and fetchall()
The fetchone() and fetchall() are the methods of Python MySQL connector and they are used to display data. This connector helps in enabling the Python programs to use MySQL databases. In the below code, we have used MySQL using Python for writing all the queries and fetching all the data from the databases. 1. Fetchone(): Fetchone() method is used
3 min read
Interface Python with an SQL Database
Python is an easy-to-learn language and connectivity of python with any SQL database is a much-desired option to have the persistence feature. Python is an object-oriented programming language and it is open source. Newcomers to the software industry including school children too can learn Python easily. Python can be downloaded easily according to
8 min read
Basic Database Concepts
The database system is an excellent computer-based record-keeping system. A collection of data, commonly called a database, contains information about a particular enterprise. It maintains any information that may be necessary to the decision-making process involved in the management of that organization. It can also be defined as a collection of i
9 min read
How to Connect Python with SQL Database?
Python is a high-level, general-purpose, and very popular programming language. Basically, it was designed with an emphasis on code readability, and programmers can express their concepts in fewer lines of code. We can also use Python with SQL. In this article, we will learn how to connect SQL with Python using the ‘MySQL Connector Python module. T
6 min read
Check if it is possible to create a polygon with a given angle
Given an angle [Tex]a [/Tex]where, [Tex]1\le a< 180 [/Tex]. The task is to check whether it is possible to make a regular polygon with all of its interior angle equal to [Tex]a [/Tex]. If possible then print "YES", otherwise print "NO" (without quotes). Examples: Input: angle = 90 Output: YES Polygons with sides 4 is possible with angle 90 degre
4 min read
Check if it is possible to create a polygon with given n sides
Given an array arr[] that contains the lengths of n sides that may or may not form a polygon. The task is to determine whether it is possible to form a polygon with all the given sides. Print Yes if possible else print No.Examples: Input: arr[] = {2, 3, 4} Output: YesInput: arr[] = {3, 4, 9, 2} Output: No Approach: In order to create a polygon with
5 min read
How to Create Rain Animation in Flash?
Flash is a 2D animation software that can be used on different operating systems like macOS, Windows, Linux, etc. It was first launched in 1996 and the latest version is released in 2021. It is capable of different functionalities like masking, character tracing, lip-sync, motion and shape tweening, frame by frame animations, etc. The animations cr
3 min read
How to Create a Shape Tween in Flash?
Flash is an extremely powerful animating tool used for making animations of different styles like frame-by-frame animation, shape tween animations, or motion tween animations. It can be used for both motion graphics and hand-drawn animations. This software is available for all types of operating systems like Windows, Mac, Linux, etc. The first vers
3 min read
How to Create a Bar Chart in Excel?
To learn how to create a Column and Bar chart in Excel, let's use a simple example of marks secured by some students in Science and Maths that we want to show in a chart format. Note that a column chart is one that presents our data in vertical columns. A bar graph is extremely similar in terms of the choices you've got but presents your data in ho
4 min read
How to Create a Motion Tween in Flash?
Flash is an animation software that is used to create different types of animations. It is a vector-based application which means that animations can be zoomed to any level without losing quality while quality gets damaged in the case of pixel-based animations. It is used to animate frame by frame which is a traditional method of animation and it i
3 min read
How to Create a Glowing Text Effect in Flash?
Flash is an animation software with different features. These features help in making fabulous animations and artwork. Some of the functions of flash are tweens, masking, character tracing, lip sync, text effects and many more. Animations in flash can be made frame by frame or using traditional character puppet animations in which a character or it
2 min read
How to Create a Moving Car Animation using Flash?
Flash is a 2D animation software that can be used on different operating systems like macOS, Windows, Linux, etc. It was first launched in 1996 and the latest version is released in 2021. It is capable of different functionalities like masking, character tracing, lip-sync, motion and shape tweening, frame by frame animations, etc. In Flash, the cre
3 min read
Create Fountain Animation with Flash
Flash is a 2D animation software that can be used on different operating systems like MacOS, Windows, Linux, etc. It was first launched in 1996 and the latest version is released in 2021. It is capable of different functionalities like masking, character tracing, lip-sync, motion and shape tweening, frame by frame animations, etc. The animations cr
3 min read
How to Create Side Walk Animation using Flash?
Flash is a 2D animation software that can be used on different operating systems like macOS, Windows, Linux, etc. It was first launched in 1996 and the latest version is released in 2021. It is capable of different functionalities like masking, character tracing, lip-sync, motion and shape tweening, frame by frame animations, etc. The animations cr
3 min read
How to Create Image Transition using Flash?
Flash is a 2D animation software that can be used on different operating systems like macOS, Windows, Linux, etc. It was first launched in 1996 and the latest version is released in 2021. It is capable of different functionalities like masking, character tracing, lip-sync, motion and shape tweening, frame by frame animations, etc. The animations cr
2 min read
Create a Sea Wave Animation using Flash
Cartoons are used since the 90s and it was very popular not in children but also in adults due to which advertising, entertainment and other industries also started adopting them and it turns out to be really useful for providing information in an easy way. With the adoption of animation, different tools were started to automate the process to make
3 min read
Create a Snowfall Animation using Flash
It was always tough to provide quality animations on time and due to this reason developers always try to build different tools and plug-ins to ease this process, so adobe made one of the best programs which are known as Flash to solve this problem. It comes with everything packed in a single product from frame-by-frame animation to vector graphics
2 min read
How to Create Eye Blink Animation using Flash?
Animations are used for a number of purposes like entertainment, advertisement, business, etc so animators use different types of tools but the most effective and efficient software is Flash. It makes the process of animation effortless and also saves time using functionalities like symbols through which older animation components can be easily use
2 min read
How to Create a Twinkling Star Effect in Flash?
Animation is a big process that involves different scenes in which small components are animated first and then everything is rendered as a whole so Flash is best for this process to animate each component separately. Symbols, instances help in reducing the size of the animation project as these can be animated once and after which can be used in a
2 min read
Create Lightning Effect using Flash
User engagement is very important for any organization to know the interest of the users and for that animation is the best way. For making animations different applications are available but the application that satisfies the need of most of the animators is Flash. It has huge potential to create every type of animation whether it be puppet animat
2 min read
How to Create a Skiing Animation using Flash?
Flash is an animation activity tool that utilizes different mechanisms to interpret the drawings to make them vectors and ease animation workflow. Launched in 1996 it allowed the users to experiment as much as possible so to give quality projects. It provides complete control over the animation to change frame rate and timing. Features like anticip
2 min read
How to Create a Stick Figure Animation using Flash?
Flash is used in a wide number of things like creating logos, gifs, vector images, animations, etc. It is a lightweight software and does not need heavy graphics so it can be used on any system with minimum requirements like a dual-core processor and 4 GB ram. From 1996 to 2021 a number of versions of flash were released but the foundation of these
2 min read
Create Weight Lifting Animation using Flash
Animating characters doing some work is a difficult task and it needs time when talking about the traditional animation methods but with the help of flash this can be divided into a certain number of keyframes and the rest of the work is done by the flash to fill the in-between frames to give the nice animation effect. These features of flash are m
2 min read
How to Create Breaking of a Pot Animation?
In flash, there are certain features like animating inside various symbols on different layers which gives the animator most of the capability to use timing and anticipation of any object or character. For example, breaking of a certain object by hitting with another object can be animated each on a different layer and the final animation can be se
2 min read
How to Create a Walking Chicken Animation on Flash?
In flash we can animate walk cycles easily, there are two types of walk cycles one is the front walk cycle and the other is the sidewalk cycle so we will animate the front walk cycle. The front walk cycle is periodic in nature as any character will move to one side and then move to the other side and this will go in the loop so we will animate a ch
3 min read
How to Create a Loading Bar Animation in Flash?
Flash is a multi-media creation platform that allows users to create interactive animations for various platforms like television, mobile screens, etc. It is built using different programming languages like Action Script, Javascript, Python, C++, etc. The development credit of flash goes to future waves, Macromedia, and adobe. It is available in ma
3 min read
Create Array by replacing any element with its immediate smaller neighbour
Given an integer array arr[] of size N, the task is to generate a new array by replacing ith element with its immediate right smaller neighbour i.e., by (i+t)th element if it is smaller. Examples: Input: N = 5, Arr[] = {4, 2, 1, 5, 3}Output: 2 1 -1 3 -1Explanation: Array elements are 4, 2, 1, 5, 3.Next to 4 is 2 which is smaller, so we print 2. Nex
4 min read
How to create a Clipping Mask using Photoshop?
Photoshop is a raster graphic design software and photo editing which allows users to manipulate and photo editing and you can use photoshop to create or edit images, posters, banners, logos, invitation cards, and various graphics as well as digital art. Photoshop allows to create and edit raster images with the number of layers and import the imag
3 min read
How to Create a Venn Diagram
Venn Diagrams are graphical figures which are used for the representation of relationships between 2 or more sets of data. They are widely used in the fields of mathematics, statistics and data analysis to visually represent similarities and distinctions between items in a set of data. In this article, we will learn about the Venn diagram, the comp
11 min read
three90RightbarBannerImg