Home >Java >javaTutorial >How to Connect Database in Java?
While writing an IT application using any programming language, data flow 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 significant loss to the business. Different methods are available today for connecting your program to a database to provide users with the information they request, collect information from users, delete the information as required by the user, and update data to the database daily. We will look into one such approach by using Java as our programming language, JDBC as a database connectivity method, and following the object-oriented approach.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
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.
By using JDBC, a programmer should be able to:
Before working with JDBC, it is required to have a database to connect to it. We will be making use of the Oracle Database for the sake of our illustration. Please download the Oracle 11g express edition from the below link.
Click Here
I already have the Oracle 10g installer ready with me, as you can see below:
Source: From my desktop
Source: From my desktop
Source: From my desktop
Source: From my desktop
Source: From my desktop
Source: From my desktop
Source: From my desktop
Source: From my desktop
A few interfaces and classes are used 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:
Source: From my desktop
Below are the interfaces that we will be using to connect to the database and perform operations over it:
Let us look at the operations we can perform as a part of the JDBC operation.
No matter what operation we perform, some basic steps would remain the same:
class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@172:.26.132.40:1521:orclilp";
con=DriverManager.getConnection(URL, USERNAME, PASSWORD);
stmt = conn.createStatement();
6. Process the result set ( optional, depends )
7. Release the resources in the final block.
As we use the Oracle database in our illustration, we need to have the required driver that Oracle should provide. 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 ideally be 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
Source: From my desktop
Many jar files should be available; however, ojdbc14.jar is the latest. The same can be used for our purpose. This jar should be added to the classpath of the project. Please check the below image.
Source: From my desktop
Let us create an artist table with the following attributes: You can directly run the SQL command line as a separate module of Oracle Express Edition. But first, you need to connect, and you can execute the “connect” command to connect to the database.
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, we must create a class called Artist Bean in the Java layer. This class should have attributes of the Artist with the above context. It will look like below:
Let us create two other Java classes with the name ArtistManagementDao and CreateTable.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); } } }
Explanation:
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(); } } } }
Explanation:
The above is the detailed content of How to Connect Database in Java?. For more information, please follow other related articles on the PHP Chinese website!