How to Connect Java (JDBC) with MySQL or Oracle Database

In this tutorial you will learn how to connect java (jdbc) with mysql or oracle database.

Java JDBC is an API used to connect with database and perform all database related operations.

 

There are few steps for connecting java with any database.

1. Register Driver Class

2. Create Connection

3. Execute Queries

4. Close Connection

How to Connect Java (JDBC) with MySQL or Oracle Database

 

1. Register Driver Class

We can register driver class by passing its name in Class.forName() method.

 

Example:

 

Driver class for Oracle: oracle.jdbc.driver.OracleDriver

Driver class for MySQL: com.mysql.jdbc.Driver

 

For using oracle or mysql database we require their jar. Download it from below link and then import in eclipse project.

Download JDBC Oracle Jar: http://www.javatpoint.com/src/jdbc/ojdbc14.jar

Download JDBC MySQL Jar: http://www.javatpoint.com/src/jdbc/mysql-connector.jar

 

If you don’t know how to import jar then read below tutorial.

Read: How to Add or Import Jar in Eclipse Project

 

2. Create Connection

We can establish connection with database using getConnection() method of DriverManager class. We have to pass the connection url, username and password for the database in the getConnection() method. After establishing the connection, it is stored in reference variable of Connection class.

 

Example:

 

Connection URL

  • For Oracle: The connection url is jdbc:oracle:thin:@localhost:1521:xe. Here our database is on local system so we have used localhost. You can replace it with any IP address. 1521 is the port number on which database is running. xe is the service name.
  • For MySQL: The connection url is jdbc:mysql://localhost:3306/mydb. Here our database is on local system so we have used localhost. You can replace it with any IP address. 3306 is the port number on which database is running. mydb is the name of the database.

 

Username

  • For Oracle the default username is system or sys.
  • For MySQL the default username is root.

 

Password

Use the password that you have given while installing the database.

 

3. Execute Queries

Now you can execute queries by using various methods provided by the JDBC API.

 

4. Close Connection

The connection can be closed by using close() method of Connection class. It’s a good practice to close the connection after doing all database related work.

 

Below I have given one example that will help you to understand how to connect jdbc with mysql or oracle database.

Example to Connect Java (JDBC) with MySQL Database

 

Example to Connect Java (JDBC) with Oracle Database

 

Comment below if you found anything incorrect or have doubts related to above java database connection tutorial.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.