Nearby lessons

120 of 125

Java - JDBC Basics

📌 What You Will Learn
  • What JDBC is and why we need it
  • Database vs DBMS
  • The modern steps to connect Java to a database
  • Statement vs PreparedStatement vs CallableStatement
  • Running queries and reading results (CRUD)
  • Transactions — making changes safe

JDBC Basics is a core concept of the Java language. This lesson explains What is JDBC?, Database vs DBMS and The Five Steps of JDBC (Updated for Modern Java) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is JDBC?

JDBC (Java Database Connectivity) is Java's standard way for a program to connect to a database, send SQL commands, and read the results.

Think of JDBC as the bridge between your Java program and the database. Your program sends SQL like SELECT * FROM student through JDBC, the database answers, and JDBC brings the rows back to Java.

Everything lives in the java.sql package.

In simple words: JDBC is the bridge between your Java program and the database. Your program sends SQL over this bridge, and JDBC brings the answer rows back to Java.

Database vs DBMS

TermMeaningExample
DatabaseThe organised collection of data (the tables themselves)student_data, employee_data
DBMS / RDBMSThe software that stores, manages and serves that dataMySQL, Oracle, PostgreSQL

You will hear database used loosely for both. Technically: MySQL is the DBMS software; inside it you create databases (collections of tables).

The Five Steps of JDBC (Updated for Modern Java)

The old books (like the one this material is based on) used the JDBC-ODBC bridge driver, which has been removed from modern JDK. Today we use the Type 4 driver provided by the database vendor (for MySQL: com.mysql.cj.jdbc.Driver). Here are the modern five steps:

  • Load the driver — register the database's driver class.
  • Get a Connection — use DriverManager.getConnection(url, user, password).
  • Create a Statement — prepare an object to carry your SQL.
  • Execute the query — run the SQL and (if any) get results.
  • Close the resources — close ResultSet, Statement and Connection (use try-with-resources).
In simple words: JDBC comes down to five steps: load the driver, get a connection, create a statement, run the SQL, and close everything. DriverManager.getConnection(...) is the one call that opens the door to the database.
Example03
JCode Cell
1import java.sql.*;
2 
3class ConnectDemo {
4 public static void main(String[] args) throws Exception {
5 // 1. Load the driver (auto-loaded in modern JDBC, but we show it)
6 Class.forName("com.mysql.cj.jdbc.Driver");
7 
8 // 2. Get the connection
9 String url = "jdbc:mysql://localhost:3306/college";
10 Connection con = DriverManager.getConnection(url, "root", "password");
11 
12 // 3 & 4. Create statement and run a query
13 Statement st = con.createStatement();
14 ResultSet rs = st.executeQuery("SELECT * FROM student");
15 
16 // 5. Read the result rows
17 while (rs.next()) {
18 System.out.println(rs.getInt("rollno") + " " + rs.getString("name"));
19 }
20 
21 // close resources
22 rs.close(); st.close(); con.close();
23 }
24}

Understanding the URL

The connection URL is just an address. Let us read it piece by piece:

Example04
JCode Cell
1jdbc:mysql://localhost:3306/college
2| | | | |
3| | | | +-- database name
4| | | +-- port (MySQL default 3306)
5| | +-- computer (localhost = this machine)
6| +-- which database software
7+-- the JDBC protocol

The Three Kinds of Statements

Statement typeBest forImportant points
StatementSimple SQL run onceSQL written as text; risk of SQL injection
PreparedStatementSQL run with values, repeated or with user inputRecommended — uses ? placeholders, prevents SQL injection, faster
CallableStatementCalling stored procedures in the databaseUses {call procedureName(?, ?)}
Trainer's Note: Security tip: never build SQL by joining strings with user input, like "SELECT * FROM t WHERE name='" + name + "'". A user can type ' OR '1'='1 and harm your data (SQL injection). Always use PreparedStatement with ? placeholders — it is the professional and safe way.
In simple words: `PreparedStatement` with `?` placeholders is the safe way to pass values. The values travel separately from the SQL, so the database never mistakes user input for commands — that is how SQL injection is prevented.
Example05
JCode Cell
1// PreparedStatement - safe and professional
2String sql = "INSERT INTO student (rollno, name) VALUES (?, ?)";
3PreparedStatement ps = con.prepareStatement(sql);
4ps.setInt(1, 101);
5ps.setString(2, "Rahul");
6ps.executeUpdate();

CRUD — The Four Basic Operations

CRUD = Create, Read, Update, Delete. Every database application is basically these four operations. Here is a complete example using PreparedStatement (modern style):

Example06
JCode Cell
1import java.sql.*;
2 
3class CRUDDemo {
4 public static void main(String[] args) throws Exception {
5 String url = "jdbc:mysql://localhost:3306/college";
6 try (Connection con = DriverManager.getConnection(url, "root", "password")) {
7 
8 // CREATE (Insert)
9 try (PreparedStatement ps = con.prepareStatement("INSERT INTO student VALUES (?,?)")) {
10 ps.setInt(1, 101); ps.setString(2, "Rahul");
11 System.out.println("Inserted: " + ps.executeUpdate());
12 }
13 
14 // READ
15 try (Statement st = con.createStatement();
16 ResultSet rs = st.executeQuery("SELECT * FROM student")) {
17 while (rs.next())
18 System.out.println(rs.getInt(1) + " - " + rs.getString(2));
19 }
20 
21 // UPDATE
22 try (PreparedStatement ps = con.prepareStatement("UPDATE student SET name=? WHERE rollno=?")) {
23 ps.setString(1, "Priya"); ps.setInt(2, 101);
24 System.out.println("Updated: " + ps.executeUpdate());
25 }
26 
27 // DELETE
28 try (PreparedStatement ps = con.prepareStatement("DELETE FROM student WHERE rollno=?")) {
29 ps.setInt(1, 101);
30 System.out.println("Deleted: " + ps.executeUpdate());
31 }
32 } // resources close automatically (try-with-resources)
33 }
34}
Output
Inserted: 1 101 - Rahul Updated: 1 Deleted: 1

executeQuery vs executeUpdate

MethodUsed forReturns
executeQuery(sql)SELECT statementsA ResultSet (the rows)
executeUpdate(sql)INSERT, UPDATE, DELETEAn int (how many rows changed)
execute(sql)Any SQL (unknown type)boolean (is it a ResultSet?)

ResultSet — Reading the Rows

A ResultSet holds the rows returned by a SELECT. rs.next() moves to the next row (returns false when finished). Then we read each column by name or index:

Example08
JCode Cell
1while (rs.next()) {
2 int rollNo = rs.getInt("rollno"); // by column name
3 String name = rs.getString(2); // by column index (1-based)
4 double marks = rs.getDouble("marks");
5}

Transactions — All or Nothing

A transaction is a group of changes that must all succeed together. For example, transferring money from one account to another — if the 'add' succeeds but the 'remove' fails, the money is wrong. Transactions protect us:

In simple words: A transaction makes a group of changes all-or-nothing. commit() saves them together, and rollback() undoes everything if any one step fails.
Example09
JCode Cell
1con.setAutoCommit(false); // start manual control
2 
3try {
4 st.executeUpdate("UPDATE account SET balance = balance - 500 WHERE id=1");
5 st.executeUpdate("UPDATE account SET balance = balance + 500 WHERE id=2");
6 con.commit(); // both changes saved together
7} catch (Exception e) {
8 con.rollback(); // undo everything on any failure
9}

Database Software — What Students Use

DatabaseGood forDriver class (Type 4)
MySQLMost common for students and freecom.mysql.cj.jdbc.Driver
OracleBig companies, advanced featuresoracle.jdbc.OracleDriver
PostgreSQLFree, powerful, modernorg.postgresql.Driver
H2 / SQLiteSmall projects, no installationorg.h2.Driver / org.sqlite.JDBC
Trainer's Note: To use a database from Java you also need its JAR driver file on the classpath. For MySQL, download the mysql-connector-j JAR and add it when compiling/running: java -cp .;mysql-connector-j.jar MyProgram (on Windows the separator is ;). In real projects, tools like Spring Boot manage this automatically.

Database vs Database Management System — Deep Dive

The classic material asks this question in detail. There are also three types of DBMS — know the difference:

TermWhat it isExample
DatabaseA memory area that stores organised data (the tables).student_data, employee_data
DBMSSoftware that manages the database — stores, retrieves, updates.MySQL, Oracle
RDBMSDBMS that stores data in tables with relations between them (uses primary keys and foreign keys).MySQL, Oracle, PostgreSQL

So the chain is: Database = the data; DBMS = the software managing it; RDBMS = the special DBMS where data lives in related tables (this is what JDBC uses).

The classic material also mentions two related ideas:

  • Data warehousing — storing huge amounts of historical data for analysis; it uses data mining techniques for fast retrieval.
  • SQL (Structured Query Language) — the language we use to talk to the DBMS. JDBC simply sends SQL to the DBMS and brings back results.
📝 Key Takeaways
  • JDBC is the bridge between Java and a database.
  • Five steps: load driver, get connection, create statement, execute SQL, close resources.
  • PreparedStatement with ? placeholders is the safe, professional choice (prevents SQL injection).
  • executeQuery returns ResultSet; executeUpdate returns row count.
  • CRUD = Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE).
  • Transactions: setAutoCommit(false) + commit/rollback for all-or-nothing changes.
  • Modern drivers are Type 4 vendor drivers (the old JDBC-ODBC bridge is removed).

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10