Basic example of Java DataBase Connectivity | Java Connectivity | RDBMS | Java Programs
Java JDBC tutorial for beginners
JDBC is a Java-based API that allows developers to connect and execute SQL queries with any relational database management system (RDBMS). It is database-independent, meaning you can use JDBC to interact with MySQL, Oracle, PostgreSQL, and more without changing your Java code significantly.
Before diving into JDBC, ensure you have the following:
To interact with a database using JDBC, follow these steps:
DriverManager
class.Statement
or PreparedStatement
to run queries.ResultSet
object.Below is a simple Java program demonstrating JDBC connectivity with an Oracle database:
package jdbc;
import java.sql.*;
class MyFirstCode {
public static void main(String args[]) {
try {
// Step 1: Load the JDBC Driver
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("Driver loaded successfully");
// Step 2: Establish the Database Connection
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@//shubham-pc:1521/orcl", "scott", "tiger");
// Step 3: Create a Statement Object
Statement st = conn.createStatement();
// Step 4: Execute SQL Query
ResultSet rs = st.executeQuery("SELECT ename, sal FROM emp");
// Step 5: Process the ResultSet
int total = 0;
int count = 0;
while (rs.next()) {
String name = rs.getString(1);
int salary = rs.getInt(2);
System.out.println(name + "\t" + salary);
total += salary;
++count;
}
System.out.println("Average salary is " + (float) total / count);
// Step 6: Close JDBC Objects
rs.close();
st.close();
conn.close();
} catch (SQLException ex2) {
System.out.println("Failed to connect to the database: " + ex2.getMessage());
} catch (ClassNotFoundException ex1) {
System.out.println("Failed to load the driver: " + ex1.getMessage());
}
}
}
SQLException
and ClassNotFoundException
to ensure robust code.Connection
, Statement
, ResultSet
) to avoid memory leaks.Java Database Connectivity (JDBC) is an essential tool for Java developers to interact with relational databases. By following the steps outlined in this guide, you can easily connect to a database, execute queries, and process results. Whether you're building a small application or a large-scale system, JDBC provides the flexibility and performance you need.
For more tutorials and updates, follow us on Instagram and Facebook. Happy coding!