Module 10 · Lambdas, Streams, Concurrency and JDBC — topic 5 of 5
Database Access with JDBC
Connecting Java to relational databases: drivers and connection URLs, Connection, PreparedStatement and ResultSet, transactions, SQL injection, and closing resources.
Learning objectives
- Connect to a database and run queries and updates with PreparedStatement
- Read results from a ResultSet and map rows to objects
- Use transactions and prevent SQL injection
Definition
JDBC (Java Database Connectivity) is the standard Java API for relational databases. A driver implements the java.sql interfaces for a particular database; your code obtains a Connection, executes SQL through Statement or PreparedStatement objects, and reads results from a ResultSet.
Introduction
Most applications keep their data in a relational database such as MySQL, PostgreSQL or SQLite. JDBC is the layer every Java database tool is built on — including Hibernate and Spring Data — so understanding it explains what those frameworks do for you.
Why it matters
Storing users, orders and products in a database is the core of most backend applications.
SQL injection, caused by building SQL from user input, is one of the most common and damaging security vulnerabilities.
Detailed explanation
Drivers. Each database vendor ships a JDBC driver as a JAR (for example mysql-connector-j, postgresql or sqlite-jdbc). Add it to the classpath (with Maven or Gradle in real projects). Modern drivers register themselves automatically; Class.forName is no longer needed.
Connecting. DriverManager.getConnection(url, user, password) returns a Connection. URLs look like jdbc:mysql://localhost:3306/college, jdbc:postgresql://localhost/college or jdbc:sqlite:college.db. Keep credentials in configuration or environment variables, never in source code.
PreparedStatement. Write SQL with ? placeholders and bind values with setString, setInt, setDouble and so on. The driver sends the values separately from the SQL text, which prevents SQL injection and lets the database reuse the query plan. Use executeQuery() for SELECT (returns a ResultSet) and executeUpdate() for INSERT/UPDATE/DELETE (returns the number of rows affected).
ResultSet is a cursor: while (rs.next()) moves to each row, and rs.getString("name"), rs.getInt("marks") read columns by name. Map each row to a record or object.
Transactions. By default each statement commits immediately (auto-commit). For several statements that must succeed or fail together — a transfer debiting one account and crediting another — call setAutoCommit(false), then commit() on success or rollback() on failure.
Resources. Connection, PreparedStatement and ResultSet must be closed; declare them in try-with-resources. Real servers use a *connection pool* (such as HikariCP) instead of opening a new connection for every request.
SQLException is checked; it carries the database's error code and SQL state.
Syntax
- Parameter indexes start at 1.
- Never concatenate user input into SQL strings.
- Close everything with try-with-resources.
Code examples
Creating a table and inserting rows
This example needs a database driver, so it isn't run on this page. With sqlite-jdbc on the classpath it prints inserted 3 rows the first time (a second run fails because the roll numbers already exist).
Why string concatenation is dangerous
SELECT * FROM users WHERE name = 'x' OR '1'='1' With PreparedStatement the input is sent as data: name = ? -> x' OR '1'='1
The concatenated query matches every row because the input changed the SQL itself. A PreparedStatement treats the whole input as a plain value.
More examples
A small DAO with queries, mapping and a transaction
Step-by-step explanation
byBranchuses a PreparedStatement with a?placeholder, so the branch name can never change the SQL.- Each ResultSet row is mapped to an immutable
Studentrecord; the method returns plain Java objects, hiding JDBC from the rest of the program — the DAO (Data Access Object) pattern. - Connection, statement and result set are all declared in try-with-resources, so they are closed even if a query fails.
transferMarksturns off auto-commit, runs two updates and commits only if both affected exactly one row.- On any failure it rolls back, so the database never contains a half-finished transfer. With the rows from the first example the program prints Asha and Meera (91 and 58), then Asha with 89 and Meera with 60.
Expected output
This example works with files or other programs, so its exact result depends on your computer. The comments in the code describe what you should see.
Practical applications
- Storing users, orders and inventory in MySQL or PostgreSQL
- Spring's JdbcTemplate and JPA/Hibernate, which use JDBC underneath
- Reporting tools that run SQL queries and export results
- Embedded SQLite databases in desktop and Android apps
Best practices
- Always use PreparedStatement for values.
- Keep JDBC code in DAO or repository classes that return domain objects.
- Use transactions for multi-step changes and a connection pool in servers.
Common mistakes
Building SQL with user input
Avoid
Prefer
Concatenation lets attackers inject SQL (for example ' OR '1'='1); placeholders send input strictly as data.
Not closing connections
Avoid
Prefer
Leaked connections exhaust the database's connection limit and eventually stop the application.
Important notes
- The JDBC examples aren't executed on this page because they need a database driver JAR; the SQL injection example runs without one.
- Store database passwords in environment variables or a secrets manager, never in source control.
Key takeaways
- JDBC: get a Connection, execute SQL with PreparedStatement, read rows from a ResultSet.
- Placeholders (?) prevent SQL injection.
- Use setAutoCommit(false), commit and rollback for transactions, and close everything with try-with-resources.
Try it yourself
- 1Write a method that inserts a new product and returns its generated id using Statement.RETURN_GENERATED_KEYS.
- 2Write a search method that finds products whose name contains a keyword, safely, using LIKE ? with the value "%" + keyword + "%".
Finished reading? Mark it complete to update your dashboard.
Suggested practice
3 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhy should you use PreparedStatement with ? placeholders for user input?
- ModerateWhat does `con.setAutoCommit(false)` let you do?
- AdvancedA transfer debits one account, then the credit statement fails. With auto-commit enabled, what is the state of the database?