JDBC Design and SQL Basics: How Java Talks to Databases
How JDBC is organized (one API, pluggable vendor drivers, DriverManager and DataSource), the four driver types, where JDBC sits in modern applications, and a refresher of SQL: tables, keys, SELECT, WHERE, LIKE, joins, NULL, grouping, INSERT, UPDATE and DELETE.
kvi5hnuCode Sprout team member12 min readOn this page
Almost every business application stores its data in a relational database such as PostgreSQL, MySQL, Oracle, SQL Server or SQLite. JDBC is the part of the Java platform that lets a program connect to such a database, send SQL statements and read the results. It has been in the JDK since 1997. The current version is JDBC 4.3, which came with Java 9. The API has been stable since then, while drivers, connection pools and frameworks built on top of it have kept evolving. (Officially, "JDBC" is a trademark and not an abbreviation, though everyone reads it as "Java Database Connectivity".)
This part of the course covers the JDBC API itself. This first article explains its design and gives a compact SQL refresher. The following articles connect to a database, run statements, use prepared statements, and work with large objects, scrollable result sets, row sets, metadata and transactions.
One API, many drivers
There are many databases, and each has its own network protocol. A pure Java library that speaks all of them would be impossible to build and maintain. JDBC splits the work instead, following the model of Microsoft's ODBC:
- The JDK defines the API: mostly interfaces such as
Connection,Statement,PreparedStatementandResultSet, in the packagesjava.sqlandjavax.sql(modulejava.sql). - Database vendors (or third parties) provide a driver: a JAR that implements those interfaces for one database.
DriverManager, or aDataSource, connects the two. You give it a database URL such asjdbc:postgresql://db.example.com/shop, and it finds a driver that accepts that URL.

Your code is written against the interfaces only. Switching from one database to another means a different driver JAR and URL, plus whatever differences exist between the SQL dialects.
Driver types
The JDBC specification sorts drivers into four types. The distinction is mostly historical now:
| Type | How it works |
|---|---|
| 1 | translates JDBC calls to ODBC and needs an ODBC driver installed. The JDK's JDBC-ODBC bridge was removed in Java 8 |
| 2 | partly Java, partly native code that calls the database's client library. Needs platform-specific installation |
| 3 | pure Java client that talks a generic protocol to a middleware server, which talks to the database |
| 4 | pure Java, speaking the database's own wire protocol directly |
Practically all current drivers are type 4. You add one dependency (for example org.postgresql:postgresql or com.mysql:mysql-connector-j) and nothing else needs to be installed. Embedded databases such as H2, HSQLDB, Apache Derby (now retired) and SQLite through its JDBC driver run inside your JVM or process, which makes them handy for tests and small tools.
Where JDBC fits
In the classic client/server setup, a desktop program connected to the database directly over JDBC. Today, the usual architecture has three tiers. A browser, mobile app or desktop client talks HTTP to a server application, and only the server talks to the database. Database credentials then never leave the server, and business rules live in one place.
On the server, you will rarely see raw JDBC in application code. Frameworks wrap it: Jakarta Persistence (JPA) with Hibernate or EclipseLink, Spring's JdbcClient and JdbcTemplate, jOOQ, MyBatis and others. All of them are built on JDBC, and when something goes wrong with transactions, connections or performance, you need to understand the layer underneath. That is why this part teaches JDBC directly.
A short SQL refresher
SQL (Structured Query Language) is the language for defining and querying relational data. A relational database stores tables. Each table has named, typed columns, and holds rows. A primary key uniquely identifies each row. A foreign key refers to the primary key of another table and so links the tables.
The examples in this part use two small tables:
CREATE TABLE suppliers (
supplier_id CHAR(4) PRIMARY KEY,
name VARCHAR(40) NOT NULL,
country VARCHAR(30)
);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(60) NOT NULL,
supplier_id CHAR(4) REFERENCES suppliers(supplier_id),
price DECIMAL(8,2)
);
Table suppliers:
| supplier_id | name | country |
|---|---|---|
| ACME | Acme Tools | USA |
| NORD | Nordic Wood | Sweden |
| SOLA | Sol Lamps | Spain |
| ZETA | Zeta Paper | NULL |
Table products:
| product_id | name | supplier_id | price |
|---|---|---|---|
| 1 | Hammer | ACME | 12.50 |
| 2 | Screwdriver set | ACME | 24.00 |
| 3 | Oak shelf | NORD | 89.90 |
| 4 | Pine stool | NORD | 35.00 |
| 5 | Desk lamp | SOLA | 42.00 |
| 6 | Linux Pocket Guide | NULL | 19.99 |
| 7 | Children's chair | NORD | 29.95 |
The supplier of each product is stored only as an ID. The supplier's name and country live once, in suppliers. If a supplier's details change, there's one row to update. Splitting data so that each fact is stored once is called normalization.
Common column types
| SQL type | Meaning | Java type in JDBC |
|---|---|---|
INTEGER/INT, SMALLINT, BIGINT | 32-, 16- and 64-bit integers | int, short, long |
DECIMAL(p,s)/NUMERIC(p,s) | exact decimal with p digits, s after the point | BigDecimal |
REAL, DOUBLE PRECISION, FLOAT(n) | binary floating point | float, double |
CHAR(n) | fixed-length string, padded with spaces | String |
VARCHAR(n) | variable-length string up to n characters | String |
BOOLEAN | true or false | boolean |
DATE, TIME, TIMESTAMP, TIMESTAMP WITH TIME ZONE | dates and times | LocalDate, LocalTime, LocalDateTime, OffsetDateTime |
BLOB, CLOB (or BYTEA, TEXT and similar) | large binary or text data | Blob, Clob, byte[], String |
Use DECIMAL for money. Binary floating point can't represent amounts like 0.10 exactly. Type names and limits vary between databases, so check your database's documentation.
Querying with SELECT
SQL keywords are case-insensitive and conventionally written in capitals. SELECT lists the columns you want, FROM names the tables, and WHERE filters the rows:
SELECT name, price FROM products WHERE price <= 30
Hammer 12.50
Screwdriver set 24.00
Linux Pocket Guide 19.99
Children's chair 29.95
SELECT * returns all columns, which is convenient for exploring but brittle in programs. Comparison uses = and <> (some databases also accept !=). Strings use single quotes, and a quote inside a string is doubled: 'Children''s chair'.
LIKE matches patterns. % stands for any sequence of characters and _ for exactly one. name LIKE '%n_x%' finds "Linux" (and would find "Unix"). name LIKE '%''%' finds names containing a quote.
Results come back in no particular order unless you ask for one. ORDER BY price DESC sorts. FETCH FIRST 3 ROWS ONLY (standard SQL) or LIMIT 3 (PostgreSQL, MySQL, SQLite, H2) keeps the first rows:
SELECT name, price FROM products ORDER BY price DESC FETCH FIRST 3 ROWS ONLY
Oak shelf 89.90
Desk lamp 42.00
Pine stool 35.00
Joining tables
Listing two tables in FROM without a condition pairs every row with every other row. That's 7 × 4 = 28 rows here, which is rarely what you want. A join keeps only matching pairs:
SELECT p.name, s.name AS supplier
FROM products p JOIN suppliers s ON p.supplier_id = s.supplier_id
ORDER BY p.name
Children's chair Nordic Wood
Desk lamp Sol Lamps
Hammer Acme Tools
Oak shelf Nordic Wood
Pine stool Nordic Wood
Screwdriver set Acme Tools
p and s are table aliases. When both tables have a column of the same name, such as name or supplier_id, you must qualify it. The older style FROM products p, suppliers s WHERE p.supplier_id = s.supplier_id gives the same result. The product without a supplier is missing, because an (inner) JOIN only keeps matches. A LEFT JOIN keeps every row of the left table and fills in NULL where there's no match. Combined with WHERE s.supplier_id IS NULL, it finds products that have no supplier, which here is the "Linux Pocket Guide".
NULL
NULL means "no value" and behaves differently from any value. Any comparison with NULL, even country = NULL, is neither true nor false but unknown, and WHERE drops such rows. So WHERE country = NULL matches nothing. Write country IS NULL or IS NOT NULL. In JDBC, a NULL column comes back as null for object types. For primitive getters like getInt, it comes back as 0 and you have to ask wasNull(), as article 59 shows.
Grouping and aggregates
Aggregate functions summarize rows: COUNT, SUM, AVG, MIN, MAX. GROUP BY forms groups, and HAVING filters the groups (whereas WHERE filters rows before grouping):
SELECT s.name, COUNT(p.product_id) AS products, AVG(p.price) AS avg_price
FROM suppliers s LEFT JOIN products p ON p.supplier_id = s.supplier_id
GROUP BY s.name
HAVING COUNT(p.product_id) > 0
ORDER BY products DESC, s.name
Nordic Wood 3 51.616666666667
Acme Tools 2 18.250000000000
Sol Lamps 1 42.000000000000
Changing data
INSERT INTO products VALUES (8, 'Tape measure', 'ACME', 7.25);
INSERT INTO products (product_id, name, price) VALUES (9, 'Gift card', 25.00);
UPDATE products SET price = price * 0.9 WHERE supplier_id = 'NORD';
DELETE FROM products WHERE supplier_id IS NULL;
Naming the columns in INSERT is safer than relying on their order. Many databases accept several rows in one INSERT ... VALUES (...), (...). UPDATE and DELETE without a WHERE clause affect every row, so be careful. The database reports how many rows were changed, and JDBC passes that count to you. Here the UPDATE changes 3 rows, rounding each new price to two decimal places as the column type requires.
The database also enforces the constraints you declared. Deleting the supplier ACME while products still refer to it fails with an integrity constraint violation (SQLState class 23; PostgreSQL and H2 report 23503, MySQL 23000), and inserting a second product with ID 1 fails because of the primary key.
The SQL sublanguage for creating tables (CREATE, ALTER, DROP) is called DDL, data definition language. The sublanguage for queries and changes (SELECT, INSERT, UPDATE, DELETE) is DML, data manipulation language. The query results above were produced with the H2 database.
The program
Runnable examples in this course can't install a real database or its driver. This demo instead implements a tiny toy driver to show what DriverManager does. It first shows that no drivers are on the class path and that connecting fails with "No suitable driver" (SQLState 08001). It then registers ToyDriver, which accepts URLs starting with jdbc:toy:. Its connection and statement objects are dynamic proxies (see the reflection articles of Core Java I) that support only a few methods. The single query it understands is answered with a CachedRowSet (article 63), which is a ready-made ResultSet implementation in the JDK. Unsupported SQL raises SQLSyntaxErrorException, and unsupported methods raise SQLFeatureNotSupportedException, just as real drivers do. A URL for another database still finds no driver.
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.*;
import java.util.logging.Logger;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.*;
public class Solution {
// A toy JDBC driver for URLs of the form jdbc:toy:<name>. Real drivers come from database
// vendors; this one exists only to show what DriverManager does with a driver.
static class ToyDriver implements Driver {
static final String PREFIX = "jdbc:toy:";
@Override public boolean acceptsURL(String url) { return url.startsWith(PREFIX); }
@Override public Connection connect(String url, Properties info) throws SQLException {
if (!acceptsURL(url)) return null; // "not my URL": DriverManager tries the next driver
System.out.println(" ToyDriver.connect(" + url + ", user=" + info.getProperty("user") + ")");
return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
new Class<?>[] { Connection.class }, (proxy, method, args) -> switch (method.getName()) {
case "createStatement" -> statement();
case "getMetaData" -> null;
case "isClosed" -> false;
case "close" -> { System.out.println(" connection closed"); yield null; }
case "toString" -> "ToyConnection[" + url + "]";
default -> throw new SQLFeatureNotSupportedException(method.getName());
});
}
static Statement statement() {
return (Statement) Proxy.newProxyInstance(Statement.class.getClassLoader(),
new Class<?>[] { Statement.class }, (proxy, method, args) -> switch (method.getName()) {
case "executeQuery" -> query((String) args[0]);
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException(method.getName());
});
}
// Understands exactly one query and answers it from a CachedRowSet (which implements ResultSet)
static ResultSet query(String sql) throws SQLException {
if (!sql.equalsIgnoreCase("SELECT name, price FROM products"))
throw new SQLSyntaxErrorException("toy driver can't run: " + sql, "42000");
CachedRowSet rows = RowSetProvider.newFactory().createCachedRowSet();
RowSetMetaData meta = new RowSetMetaDataImpl();
meta.setColumnCount(2);
meta.setColumnName(1, "NAME"); meta.setColumnType(1, Types.VARCHAR);
meta.setColumnName(2, "PRICE"); meta.setColumnType(2, Types.DECIMAL);
rows.setMetaData(meta);
Object[][] data = { { "Hammer", "12.50" }, { "Oak shelf", "89.90" }, { "Desk lamp", "42.00" } };
for (Object[] row : data) {
rows.moveToInsertRow();
rows.updateString(1, (String) row[0]);
rows.updateBigDecimal(2, new java.math.BigDecimal((String) row[1]));
rows.insertRow();
}
rows.moveToCurrentRow();
rows.beforeFirst();
return rows;
}
@Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { return new DriverPropertyInfo[0]; }
@Override public int getMajorVersion() { return 1; }
@Override public int getMinorVersion() { return 0; }
@Override public boolean jdbcCompliant() { return false; }
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); }
}
public static void main(String[] args) throws SQLException {
System.out.println("drivers found on the class path: " + DriverManager.drivers().count());
try {
DriverManager.getConnection("jdbc:toy:shop");
} catch (SQLException e) {
System.out.println("before registering: " + e.getMessage() + " (SQLState " + e.getSQLState() + ")");
}
DriverManager.registerDriver(new ToyDriver()); // real drivers do this automatically
System.out.println("drivers now: " + DriverManager.drivers().map(d -> d.getClass().getSimpleName()).toList());
System.out.println("--- connecting through DriverManager ---");
try (Connection conn = DriverManager.getConnection("jdbc:toy:shop", "ada", "secret");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT name, price FROM products")) {
System.out.println(" got " + conn);
while (rs.next())
System.out.printf(" %-10s %6s%n", rs.getString("NAME"), rs.getBigDecimal("PRICE"));
try {
stat.executeQuery("DROP TABLE products");
} catch (SQLException e) {
System.out.println(" " + e.getClass().getSimpleName() + ": " + e.getMessage() + " [" + e.getSQLState() + "]");
}
try {
conn.prepareStatement("SELECT 1");
} catch (SQLFeatureNotSupportedException e) {
System.out.println(" not supported: " + e.getMessage());
}
}
System.out.println("--- a URL for a different database ---");
try {
DriverManager.getConnection("jdbc:postgresql://localhost/shop");
} catch (SQLException e) {
System.out.println(" " + e.getMessage());
}
}
}
drivers found on the class path: 0
before registering: No suitable driver found for jdbc:toy:shop (SQLState 08001)
drivers now: [ToyDriver]
--- connecting through DriverManager ---
ToyDriver.connect(jdbc:toy:shop, user=ada)
got ToyConnection[jdbc:toy:shop]
Hammer 12.50
Oak shelf 89.90
Desk lamp 42.00
SQLSyntaxErrorException: toy driver can't run: DROP TABLE products [42000]
not supported: prepareStatement
connection closed
--- a URL for a different database ---
No suitable driver found for jdbc:postgresql://localhost/shop
Real drivers register themselves. Each driver JAR lists its Driver class in META-INF/services/java.sql.Driver, and DriverManager loads them through the ServiceLoader (article 58). That's why the old Class.forName("org.postgresql.Driver") line is no longer needed.
Common questions
Should I learn JDBC if I'm going to use JPA or Spring anyway? Yes, at least the basics. Frameworks generate JDBC calls, and their error messages, logs, connection-pool settings and transaction behavior all speak JDBC. Debugging "connection leak", "too many connections" or "lock timeout" problems is much easier when you know what happens underneath.
Which database should I practice with? H2 or SQLite for zero setup, PostgreSQL (in Docker) for something close to production. PostgreSQL is free, standards-friendly, and the most common choice for new server applications.
Is SQL the same in every database?
The core (SELECT, JOIN, INSERT, UPDATE, DELETE, GROUP BY) is portable. Differences show up in data types, row limiting (LIMIT vs FETCH FIRST), auto-generated keys, string functions, date arithmetic, upserts and identifier case. Test against the database you deploy on, not just an in-memory substitute.
What's the difference between JDBC and ODBC? ODBC is a C API with the same idea, mostly used on Windows and by non-Java tools. JDBC is the Java equivalent. The old JDBC-ODBC bridge was removed in Java 8, so Java programs use native JDBC drivers.
What about NoSQL databases such as MongoDB or Redis? They have their own Java client libraries and don't use JDBC, because they don't speak SQL. Some offer JDBC drivers for reporting tools, with limited SQL support.
API reference
| API | Purpose |
|---|---|
java.sql.Driver.connect(url, info), acceptsURL(url) | the interface every driver implements |
DriverManager.getConnection(url, user, password) | open a connection through a matching driver |
DriverManager.drivers(), registerDriver(driver) | inspect and register drivers |
Connection.createStatement(), Statement.executeQuery(sql) | run SQL (article 59) |
ResultSet.next(), getString, getBigDecimal | read results |
SQLException.getSQLState(), SQLSyntaxErrorException, SQLFeatureNotSupportedException | errors |
javax.sql.DataSource | the preferred way to obtain connections (article 58) |
javax.sql.rowset.CachedRowSet | a disconnected, in-memory ResultSet (article 63) |
Summary
- JDBC is an API of interfaces in
java.sqlandjavax.sql. Vendors supply drivers that implement them, andDriverManageror aDataSourcepicks the driver from the URL. - Modern drivers are pure Java (type 4) and come as a single JAR. Embedded databases run in your process.
- Most applications use JDBC on the server side, often through JPA, Spring or jOOQ, but the concepts carry through all of them.
- SQL basics:
SELECT ... FROM ... WHERE ... ORDER BY, joins via matching keys,LEFT JOINfor optional matches,IS NULLfor missing values,GROUP BYandHAVINGwith aggregates, andINSERT,UPDATE,DELETEfor changes. - Use
DECIMALfor money, name columns explicitly, and remember thatUPDATEandDELETEwithoutWHEREhit every row.
Practice Questions
Why doesn't the JDK include drivers for PostgreSQL or Oracle?
Each database speaks its own protocol, and it changes with database versions. JDBC defines only the interfaces, and the database vendors, who know their protocols best, supply and update the drivers independently of JDK releases. You add the driver for your database as a dependency.
Write a query that lists each supplier's name with the number of its products, including suppliers that have none.
SELECT s.name, COUNT(p.product_id) FROM suppliers s LEFT JOIN products p ON p.supplier_id = s.supplier_id GROUP BY s.name. The LEFT JOIN keeps suppliers without products, and COUNT(p.product_id) counts only non-NULL values, so they get 0. COUNT(*) would count the NULL-filled row and report 1.
Why does SELECT * FROM suppliers WHERE country = NULL return no rows even though one supplier has no country?
A comparison with NULL yields "unknown", not true, and WHERE keeps only rows where the condition is true. Use WHERE country IS NULL.
What does DELETE FROM products (with no WHERE clause) do, and how can the database protect you from deleting a supplier that is still referenced?
It deletes every row in the table. A foreign key constraint (REFERENCES suppliers(supplier_id)) makes the database refuse to delete a supplier that products still refer to, failing with an integrity constraint violation. Alternatively, ON DELETE CASCADE deletes the referring rows too, or ON DELETE SET NULL clears their reference.
A connection attempt fails with "No suitable driver found for jdbc:postgresql://...". What are the likely causes?
The PostgreSQL driver JAR isn't on the class path (or module path), so no registered driver accepts the URL. The other common cause is a typo in the URL prefix, so that no driver recognizes it. Add the driver dependency and check the URL format in the driver's documentation.
Previous: Sending Email from Java: SMTP and Jakarta Mail
Next: Connecting to a Database with JDBC: URLs, Drivers, DriverManager and DataSource
Related reading
- Sending Email from Java: SMTP and Jakarta Mail
- A Simple HTTP Server in Java: jwebserver, HttpServer, Handlers and Filters
- Asynchronous HTTP and WebSocket in Java: sendAsync, HTTP/2 and WebSocket
- The Java HttpClient: Requests, Responses, Body Publishers and Handlers
- Posting Form Data in Java: GET and POST, URL Encoding and Multipart

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.