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
Loading editor…

Understanding the URL

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

Example04
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.