EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

How to Connect Database in Java?

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Java Tutorial » How to Connect Database in Java?

How to Connect Database in Java?

How to Connect Database in Java?

While writing an IT application using any programming language, the flow of data from and to the application serves the core functionality. If the data flow is somehow affected, it can adversely affect the application functionality and may cause a big loss to the business. There are different methods available today for connecting your program to a database in order to provide users with the information they request for, collect information from users, delete the information as required by the user and also to update data to the database on daily basis. We are going to look into one such approach by using Java as our programming language, JDBC as database connectivity method and following the object-oriented approach.

What is JDBC?

JDBC stands for Java Database Connectivity and it helps a Java program to perform different kinds of operations over the database such as create, read, update and delete. Also, JDBC is a Java API.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

By using JDBC, a programmer should be able to:

  • Establish a connection with Database
  • Run SQL commands by sending it to Database
  • Interprets the results that come from Database

Creating a Database to Connect Database in Java

Before working with JDBC, it is required to have a database in order to connect to it. We will be making use of the Oracle Database for the sake of our illustration. Please download oracle 11g express edition from below link.

Click Here

I already have Oracle 10g installer ready with me as you can see below:

Connect Database in Java 1

Source: From my desktop

  • Please double click the installer, below screen will pop up. Click next.

Connect Database in Java 2

Source: From my desktop

  • Please accept the license agreement and click on next.

Connect Database in Java 3

Source: From my desktop

  • Please keep the default settings as they and click on next.

Connect Database in Java 4

Source: From my desktop

  • It will ask for a password that will be required when you log in to Oracle 11g instance. Please provide the password and click on next.

Connect Database in Java 5

Source: From my desktop

  • After you provide the password, the installation process will begin. Once the installation is finished, a shortcut icon shall get created on your desktop screen. If you are not able to find it, please go to windows start and search for Oracle, you should get it. Click on it and it will open a thin client for you via a browser. Log in to the instance. Please note down that the username will be the same for the Oracle DB i. e. system. The password will be the one that you had provided while configuring the database.

Connect Database in Java 6

Source: From my desktop

  • Now once you log in,  the very first screen that you will see will look like below:

Connect Database in Java 7

Source: From my desktop

  • Now let’s create a table. Please click on the SQL module from the above screen and run the below query.

Connect Database in Java 8

Source: From my desktop

  • As you can see, we have successfully created a table with the name Educba.

Connect Database in Java

There are a few interfaces and classes that are used in order to connect to a database and perform operations using JDBC API.

We will explain one by one, but let me first present to you the below program:

Popular Course in this category
All in One Data Science Bundle (360+ Courses, 50+ projects)360+ Online Courses | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (3,220 ratings)
Course Price

View Course

Related Courses
Java Training (40 Courses, 29 Projects, 4 Quizzes)JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes)jQuery Training (8 Courses, 5 Projects)Java Training (40 Courses, 29 Projects, 4 Quizzes)Free Java Online CourseJavaFX Training (1 Courses)Java Training (40 Courses, 29 Projects, 4 Quizzes)

Connect Database in Java 9

Connect Database in Java 10

Connect Database in Java 11

Source: From my desktop

Below are the interfaces which we will be using to connect to the Database and perform operations over it:

  1. Driver Manager
  2. Connection
  3. Statement
  4. Result set
  5. Prepared statement

Let us look at the operations that we can perform as a part of the JDBC operation.

  1. Store the data from an entity to a database i.e. the create operation
  2. Retrieve the data to the entity or a bean from a database
  3. Update the data for the entity or the bean in the database
  4. Delete or remove the data on the entity or a bean from the database.

No matter what operation do we perform, there are some basic steps that would remain the same:

  1. Load the driver.

Class.forName("oracle.jdbc.driver.OracleDriver");

  1. Create a URL string

String url="jdbc:oracle:thin:@172:.26.132.40:1521:orclilp";

  1. Use the driver manager to create a connection

con=DriverManager.getConnection(URL, USERNAME, PASSWORD);

  1. Use Connection reference to create Statement

stmt = conn.createStatement();

  1. Use a statement to execute the query

Connect Database in Java 12

6. Process the result set ( optional, depends )

7. Release the resources in the finally block.

Connect Database in Java 13

Illustration

As we are using the Oracle database in our illustration, we need to have the required driver that should be provided by Oracle. The driver class is usually in the form of a jar file with the name ojdbc14.jar. This driver should be imported to your java program as a part of  “ Referenced Libraries ”  if it is not there.

If you have installed Oracle 11g in your C folder, it can be ideally found in the below path: ( If it is not there, it can be easily downloaded from here )

C: \ oraclexe\ app\ oracle\ product\ 10.2.0\ server\ jdbc\ lib

Connect Database in Java 14

Source: From my desktop

A lot of jar files should be available however ojdbc14.jar is the latest one. The same can be used for our purpose. This jar should be added to the classpath of the project. Please check the below image.

Connect Database in Java 15

Source: From my desktop

Let us create an artist table with the following attributes: ( You can directly run the SQL command line which comes as a separate module of Oracle Express Edition. But first, you need to connect and you can execute the  ” connect ” command in order to connect to the database.

Connect Database in Java 16

Source: From my desktop

As a part of this illustration, we would be creating three java classes i.e. Artist.java, CreateTable.java and ArtistManagementDao.java to achieve this.

Also in the java layer, we need to create a class called Artist bean. This class should have attributes of the Artist with the above context. It will look like below:

Artist.java

Connect Database in Java 17

Let us create 2 other java classes with the name ArtistManagementDao and CreateTable.java

ArtistManagementDao.java

package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ArtistManagementDao {
private final static String DRIVERNAME="oracle.jdbc.driver.OracleDriver";
private final static String URL="jdbc:oracle:thin:@LENOVO-PC:1521:XE";
private final static String USERNAME="System";
private final static String PASSWORD="Your DB password";
private Connection con =null;
public void addArtist(Artist a)
{
try {
Class.forName(DRIVERNAME);
String sql="insert into Artist1 values (?,?)";
con=DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1, a.getArtistID());
pst.setString(2, a.getArtistName());
pst.executeUpdate();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(e);
} catch (SQLException e) {
System.out.println(e);
}
}
}

CreateTable.java

package com;
import java.sql.*;
public class CreateTable{
static final String DB_URL = "jdbc:oracle:thin:@LENOVO-PC:1521:XE";
static final String USER = "System";
static final String PASS = "Your DB Password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
ArtistManagementDao am=new ArtistManagementDao();
Artist a=new Artist();
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected to database successfully");
System.out.println("Creating table");
stmt = conn.createStatement();
//ARTIST TABLE
String sql = "CREATE TABLE Artist3 " +
"(ArtistID varchar2(5) primary key not NULL, " +
" ArtistName varchar2(25))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
a.setArtistId("abc");
a.setArtistName("ankit");
am.addArtist(a);
System.out.println("\nArtistID="+a.getArtistID()+"\nArtistName="+a.getArtistName());
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}

CreateTable.java Explanation:

  1. We have first created DB URL which should have your computer name, as well as DB port number ( ideally 1521 ),  preceded by JDBC:oracle:thin:@. Then we have created username and password in order to pass these attributes during the time of Database connection. It is highly recommended to encrypt these values in the production environment.
  2. In the CreateTable.java class, we have created an object “ am ” and “ a ” of ArtistManagementDao.java and Artist.java class respectively.
  3. Then we tried to establish our connection by following the steps that we have learned earlier using a conn statement.
  4. Then we have created a table with name Artist3 and updated the database or pushed this to the database using the execute the statement.
  5. Now if we would like to assign values to the attributes, we will make use of the object that we have created for artist class and make a note, it is not this class that will insert the value to Database, rather it will be ArtistmanagementDao class. We already have stored values in attributes as of now and we will see in day class how to push this to the database.
  6. Finally, we have used the ” am ” object from ArtistManagementDao to pass this object “a” to method addArtist() of ArtistManagementDao java class.
  7. We have also used to try and catch block for catching any exceptions and throwing out the same.

ArtistManagementDao Explanation:

  1. The Dao class helps us to isolate the application/business layer from the persistence layer. This is usually the relational database.
  2. We have first created DB URL which should have your computer name, as well as DB port number ( ideally 1521 ), preceded by JDBC:oracle:thin:@. Then we have created username and password in order to pass these attributes during the time of Database connection. It is highly recommended to encrypt these values in the production environment.
  3. Inside the addArtist method, we tried to establish our connection by following the steps that we have learned earlier using a conn statement.
  4. Now, we have used the insert method to push values from attributes to the database.
  5. In the next statement, in order to test, we have the get statement to retrieve values from the database.
  6. We have also used to try and catch block for catching any exceptions and throwing out the same.

Recommended Articles

This has been a guide on how to connect database in java. Here we have discuss how to connect the database in java along with interfaces and classes used in order to connect a database. You may also look at the following articles to learn more –

  1. What is SQL Server?
  2. Is Big Data a Database?
  3. How JavaScript Works
  4. Multithreading Interview Questions in Java

 

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

4 Shares
Share
Tweet
Share
Primary Sidebar
Java Tutorial
  • Advanced
    • Methods in Java
    • Serialization in Java
    • Inner Class in Java
    • Anonymous Inner Class in Java
    • Java Stack Methods
    • Java Static Nested Class
    • Synchronized Block in Java
    • Static Synchronization in Java
    • Abstract Class in Java
    • Access Modifiers in Java
    • Non Access Modifiers in Java
    • Bit Manipulation in Java
    • Encapsulation in Java
    • Singleton Class in Java
    • Wrapper Class in Java
    • Nested Class in Java
    • Java Matcher
    • Java Pattern Class
    • Java File Class
    • Final Class in Java
    • Stack Class in Java
    • Anonymous Class in Java
    • StringBuilder Class in Java
    • StringBuffer in Java
    • Java Directories
    • JSON in Java
    • Object Class in Java
    • What is Multithreading in java
    • Java Thread Priority
    • Daemon Thread in Java
    • Java Thread Pool
    • Java ThreadLocal
    • Association in Java
    • Queue in Java
    • Functional Programming in Java
    • ClassLoader in Java
    • Interface in Java
    • Functional Interface in Java
    • Java Queue Interface
    • Collection Interface in Java
    • Object Cloning in Java
    • Java.net URI
    • Java Assertion
    • Vector in Java
    • Applets in Java
    • Template in Java
    • Java Shutdown Hook
    • 2D Graphics in Java
    • Autoboxing and Unboxing in Java
    • Comparable in Java Example
    • Java Annotations
    • Java User Input
    • Serialization in Java
    • Dynamic Binding in Java
    • Java Parse String
    • Java Adapter Classes
    • Immutable Class in Java
    • String Initialization in Java
    • String Manipulation in Java
    • ThreadGroup in Java
    • Java Iterate Map
    • Java IO
    • Java?OutputStreamWriter
    • DataInputStream in Java
    • Java BufferedReader
    • Java BufferedWriter
    • Java BufferedInputStream
    • Java ByteArrayInputStream
    • Java ByteArrayOutputStream
    • Java RandomAcessFile
    • Java PrintStream
    • Java PrintWriter
    • Java URLEncoder
    • Java Scanner Class
    • Java Console
    • Java Runtime class
    • Java Base64
    • Java Base64 Encoding
    • Java Base64?Decode
    • Finalize in Java
    • Java Parallel Stream
    • Java Getter Setter
    • Set Interface in Java
    • How to Connect Database in Java
    • How to Create Webservice in Java
    • Composition in Java
    • BinarySearch() in Java
    • Exception Handling in Java
    • Java NullPointerException
    • Java NoSuchElementException
    • Java ConcurrentModificationException
    • Java ArithmeticException
    • Java IOException
    • Java RuntimeException
    • NumberFormatException in Java
    • Java ArrayIndexOutOfBoundsException
    • Java ClassNotFoundException
    • Java FileNotFoundException
    • Java InterruptedException
    • Finally in Java
    • Java Default Method
    • Java Locale
    • Tuples in Java
    • Java ServerSocket
    • Java Lambda Expressions
    • Java DatagramSocket
    • Java Animation
  • Basic
    • What is Java?
    • What is JNDI in Java
    • What is JNI in Java
    • What is Java Interface
    • What is Java SE
    • What is JavaBeans
    • Install JDK
    • Java Programming Language Features
    • Applications of Java
    • Career in Java
    • Versions of Java
    • Java Virtual Machine
    • Java GUI Framework
    • Java Packages
    • Java Package Example
    • Default Package in Java
    • Variables in Java
    • Instance Variable in Java
    • Object in Java
    • Java Commands
    • Iterator in Java
    • Java Booleans
    • Conversion in Java
    • Type Conversion in Java
    • String in Java
    • What is JDK
    • What is JVM
    • What is J2EE
    • RMI Architecture
    • Java Literals
    • Data Types in Java
    • Primitive Data Types in Java
    • Enumset in Java
    • Cheat Sheet Java
    • IntelliJ Cheat Sheet
  • Frameworks
    • Best Java Compilers
    • Frameworks In Java
    • Testing Frameworks for Java
    • Java Monitoring Tool
    • Best Java IDE
    • Java Compilers
    • Java Tools
    • Java Deployment Tools
    • Types of Memory in Java
    • Java References
    • Java Type Inference
    • Java Boolean to String
    • Java String to Float
    • java.net Package
    • Java Formatter
  • Operators
    • Arithmetic Operators in Java
    • Unary Operators in Java
    • Logical Operators in Java
    • Comparison Operators in Java
    • Assignment Operators in Java
    • Java String Operators
    • Conditional Operator in Java
    • Boolean operators in Java
  • Keywords
    • Java Keywords
    • this Keyword in Java
    • Static Keyword in Java
    • Native keyword in Java
    • Throw Keyword in Java
    • Throws Keyword in Java
    • What is public in Java?
    • Private in Java
    • Protected Keyword in Java
    • Final Keyword in Java
  • Control statements
    • Control Statement in Java
    • Else-If Statement in Java
    • Nested if Statements in Java
    • Continue Statement in Java
    • Break Statement in Java
    • Case Statement in Java
  • Loops
    • Loops in Java Programming
    • For Loop in Java
    • While Loop in Java
    • do-while loop in Java
    • For-Each loop in Java
    • Nested Loop in Java
  • Inheritance
    • Inheritance in Java
    • Single Inheritance in Java
    • Multilevel Inheritance in Java
    • Hierarchical Inheritance in Java
    • Hybrid Inheritance in Java
  • Constructor and destructor
    • Constructor and Destructor in Java
    • Constructor in Java
    • Destructor in Java
    • Copy Constructor In Java
    • Static Constructor in Java
    • Private Constructor in Java
  • Array
    • Arrays in Java Programming
    • 2D Arrays in Java
    • 3D Arrays in Java
    • Multidimensional Array in Java
    • Array Methods in Java
    • Print 2D Array in Java
    • Print Array in Java
    • String Array in Java
    • Associative Array in Java
    • Dynamic Array in Java
    • Java Array Iterator
    • Java array.push
    • Sort String Array in Java
  • Sorting
    • Sorting in Java
    • Sorting Algorithms in Java
    • Merge Sorting Algorithms in Java
    • Quick Sorting Algorithms in Java
    • Selection Sort In Java
    • Heap Sort In Java
    • Bubble Sort in Java
    • Merge Sort In Java
    • Quick Sort in Java
    • Insertion Sort in Java
    • Sort String in Java
    • Program for Merge Sort in Java
  • Functions
    • String Functions in java
    • Math Functions in Java
    • Hashing Function in Java
    • Regular Expressions in Java
    • Recursion in Java
    • Java Callback Function
    • Java Call by Value
    • Java Call by Reference
    • HashMap in Java
    • Java String Concatenation
    • Java String Equals
    • Compare two Strings in Java
    • Virtual Function in Java
    • Java newInstance()
    • split() Function in Java
    • trim() Function in Java
    • Replace() Function in Java
    • substring() Function in Java
    • Strictfp in Java
    • String Reverse Function in Java
    • Java String getBytes
    • Java Replace Char in String
    • Shuffle() in Java
    • addAll() in Java
    • FileWriter in Java
    • Java Stream Filter
    • Java FileInputStream
    • replaceAll() in Java
    • repaint in Java
    • copy() in Java
    • Java max()
    • Java min()
    • Java Timestamp
    • Java URLConnection
    • Java StringJoiner
    • Java KeyStore
    • Java InetAddress
    • Java getMethod()
    • swap() in Java
    • Deadlock in Java
    • Range in Java
    • Java Repository
    • Java Dictionary
    • Calculator in Java
    • Mutable String in Java
    • Mutable vs Immutable Java
    • Native Methods in Java
    • StringBuffer Class in Java
    • String Class in Java
    • Java URL Class
    • Java Vector Class
  • Polymorphism
    • What is Polymorphism
    • Polymorphism in Java
    • Runtime Polymorphism in Java
    • Overloading and Overriding in Java
    • Overloading in Java
    • Method Overloading in Java
    • Function Overloading in Java
    • Overriding in Java
    • Method Overriding in Java
    • Final Keyword in Java
    • Super Keyword in Java
    • instanceOf in Java
    • Java Authenticator
    • Java Alias
  • Collections
    • What is TreeMap in Java?
    • Sorting in Collection
    • Java Collections Class
    • Hashtable in Java
    • Java EnumMap
    • Java LinkedHashMap
    • Reverse Linked List in Java
    • LinkedList in Java
  • Date Time
    • java.util.Date
    • Java Clock
    • Java Instant
    • Java LocalTime
    • Java ZoneId
    • Java ZoneOffset
    • Java varargs
    • Java LocalDate
    • Java OffsetDateTime
    • Java LocalDateTime
    • Java Duration
    • Java DayOfWeek
    • Java Period
    • Timer in Java
    • Java TimeZone
    • Java Date Picker
  • MISc
    • What is Synchronization in Java
    • What is Concurrency in Java
    • What is Design Pattern in Java
    • What is Generics in Java
    • What is API in Java
    • What is a Binary Tree in Java
    • What is Java Garbage Collector
    • What is Java Inheritance
    • Thread Life cycle in Java
    • Object Oriented Programming in Java
    • Java App Development
    • Java Naming Conventions
    • Java hashCode()
    • Java Transient
    • JSTL In Java
    • Comparable in Java 
    • Aggregation in Java
    • EJB in Java
    • @deprecated in Java
    • Java @Inherited
    • @SuppressWarnings in Java
    • Java @Override
  • Programs
    • Patterns in Java
    • Star Patterns in Java
    • Number Patterns in Java
    • Swapping in Java
    • Factorial in Java
    • Fibonacci Series in Java
    • Reverse Number in Java
    • Palindrome in Java
    • Armstrong Number in Java
    • Squares in Java
    • Square Root in Java
    • Special Number in Java
    • Anagram Program in Java
    • Strong Number in Java
    • Random Number Generator in Java
    • Matrix Multiplication in Java
    • Socket Programming in Java
    • Prime Numbers in Java
    • String Comparison in Java
    • Leap Year Program in Java
    • Reverse String in Java
    • Design Patterns in Java
    • Happy Numbers in Java
  • Interview Questions
    • Java Interview Questions
    • Java Inheritance Interview Questions
    • Java EE Interview Questions
    • Java Developer Interview Questions
    • Java Collection Interview Questions
    • Java Interview Question on Multithreading
    • Java String interview question
    • Java Testing Interview Questions
    • Java Multi-threading Interview Questions
    • Multithreading Interview Questions in Java
    • Oops Java Interview Questions
    • Java Spring Interview Questions
    • Data Structure Java Interview Questions
    • Java Web Services Interview Questions

Related Courses

Java Course

JavaScript Certification Course

jQuery Training Course

Java Training Courses

Free Java Training Courses

JavaFX Training

Java Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - All in One Data Science Bundle (360+ Courses, 50+ projects) Learn More