🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Java JDBC — Connect Java to MySQL Database

Java Advanced TopicsJDBC and Databases🟢 Free Lesson

Java JDBC — Connect Java to MySQL Database

Learning Objectives

  • Describe the role of JDBC and a database driver
  • Open a connection to a MySQL database
  • Execute inserts, updates, and selects safely
  • Read results from a ResultSet and close resources

Overview

JDBC stands for Java Database Connectivity. It is an API in the Java standard library that lets programs send SQL statements to relational databases and process the answers. MySQL, PostgreSQL, Oracle, and SQL Server all work through JDBC once you have the right driver.

A driver is a small library that translates generic JDBC calls into the wire protocol of a specific database. Modern MySQL connectors auto-register through the service provider mechanism, so you rarely load drivers manually, but understanding the flow helps when configuration fails.

The JDBC Workflow

Every database interaction follows the same broad sequence of steps.

StepJDBC conceptTypical type
1Establish connectionConnection
2Create statementPreparedStatement
3Execute SQLexecuteUpdate or executeQuery
4Read resultsResultSet
5Close resourcesclose methods

Keeping this order in mind makes even long methods easier to debug, because you can check each stage when something breaks.

Connecting to MySQL

You need the JDBC URL, a username, and a password. The URL names the protocol, the host, the port, the database, and optional parameters such as time zone settings required by recent MySQL versions.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/school"
            + "?serverTimezone=UTC";
        String user = "root";
        String password = "secret";

        try {
            Connection connection = DriverManager.getConnection(url, user, password);
            System.out.println("Connected: " + !connection.isClosed());
            connection.close();
        } catch (SQLException e) {
            System.out.println("Connection failed: " + e.getMessage());
        }
    }
}

Add the MySQL connector jar to your project classpath before running. Connection failures usually mean wrong credentials, a database that is not running, or a port and database name mismatch.

Inserting with PreparedStatement

PreparedStatement separates SQL structure from data. Values are supplied with placeholders, and the driver handles escaping. That design prevents SQL injection, a serious security flaw where untrusted text alters your query structure.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/school";
        String sql = "INSERT INTO students (name, grade) VALUES (?, ?)";

        try (Connection connection = DriverManager.getConnection(url, "root", "secret");
             PreparedStatement ps = connection.prepareStatement(sql)) {

            ps.setString(1, "Ada");
            ps.setInt(2, 95);
            int rows = ps.executeUpdate();

            System.out.println("Rows inserted: " + rows);
        } catch (SQLException e) {
            System.out.println("Insert failed: " + e.getMessage());
        }
    }
}

executeUpdate returns the count of affected rows and is used for insert, update, and delete statements that do not return rows.

Querying with ResultSet

Queries use executeQuery, which returns a ResultSet: a cursor over matching rows. Loop with next and read columns by label or index.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/school";
        String sql = "SELECT name, grade FROM students WHERE grade > ?";

        try (Connection connection = DriverManager.getConnection(url, "root", "secret");
             PreparedStatement ps = connection.prepareStatement(sql)) {

            ps.setInt(1, 90);

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    String name = rs.getString("name");
                    int grade = rs.getInt("grade");
                    System.out.println(name + ": " + grade);
                }
            }
        } catch (SQLException e) {
            System.out.println("Query failed: " + e.getMessage());
        }
    }
}

In the source file the where clause uses the greater than operator between grade and the placeholder so the query filters grades above the bound. The surrounding try-with-resources closes the connection and statement even if reading throws.

Updates and Deletes

Updates and deletes follow the PreparedStatement pattern with executeUpdate. Parameter binding stays the same; only the SQL text changes. Always validate and log affected row counts so silent mismatches surface early in development.

Best Practices

Reuse connections through a pool in production instead of opening one per request. Never concatenate untrusted input into SQL. Keep credentials outside source code in configuration or environment variables. Close every resource with try-with-resources. For read heavy applications, consider batch inserts with addBatch and executeBatch to reduce round trips.

Key Takeaways

💡

  • JDBC connects Java programs to relational databases through a driver
  • PreparedStatement prevents SQL injection and is the default choice
  • executeUpdate handles data change statements; executeQuery returns a ResultSet
  • ResultSet.next advances the cursor before reading column values
  • try-with-resources closes connections, statements, and result sets reliably

Practice Questions

  1. List the five main JDBC steps involved in running a select query.
  2. Why is concatenating user input directly into SQL dangerous compared with placeholders?
  3. Write a small program that inserts two rows and then selects and prints all rows.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Java Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement