Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 57

JDBC with MySQL in Java

In this lesson: Connect Java to MySQL with JDBC — driver, Connection, PreparedStatement, insert and select — full code. In Hindi & English.

What is JDBC

JDBC (Java Database Connectivity) is the standard way for Java programs to talk to databases like MySQL. With it, you open a connection, send SQL queries, and read back the results — all from Java code. It is the foundation of database work in Java.

💡 JDBC steps: load driver → connect → prepare a query → execute → read results → close.

The JDBC steps

  1. Add the MySQL JDBC driver to your project.
  2. Get a Connection with the database URL, user and password.
  3. Create a PreparedStatement for your SQL.
  4. Execute it and get a ResultSet (for SELECT).
  5. Loop the results and read each column.
  6. Close the resources.

Connecting to MySQL

import java.sql.*;

String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String pass = "password";

Connection con = DriverManager.getConnection(url, user, pass);
System.out.println("Connected!");
Connected!

DriverManager.getConnection opens the connection using the database URL, username and password. The URL points to the MySQL server and the database name.

Running a query

String sql = "SELECT name, marks FROM students WHERE marks > ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 40);              // fill the ? placeholder
ResultSet rs = ps.executeQuery();

A PreparedStatement uses ? placeholders for values, which you fill with setInt, setString, etc. executeQuery runs a SELECT and returns a ResultSet.

Reading results

while (rs.next()) {
    String name = rs.getString("name");
    int marks = rs.getInt("marks");
    System.out.println(name + ": " + marks);
}
rs.close(); ps.close(); con.close();
Aman: 88
Diya: 92

Loop with rs.next() to move through the rows, reading each column by name. Always close the ResultSet, statement and connection when done to free resources.

Prevent SQL injection

// SAFE: placeholder, input treated as data
PreparedStatement ps =
    con.prepareStatement("SELECT * FROM users WHERE email = ?");
ps.setString(1, userInput);

// UNSAFE: never build SQL by joining input
// "... WHERE email = '" + userInput + "'"

Always use a PreparedStatement with ? and setString. This treats input as data, never as SQL, which stops injection attacks — the same rule as in PHP and every language.

Common mistakes

  • Building SQL with string joins. Use PreparedStatement placeholders to stay safe.
  • Not closing resources. Close ResultSet, statement and connection (or use try-with-resources).
  • Missing the driver. The MySQL JDBC driver must be on the classpath.
  • Wrong column name in getString. It must match the SELECT column exactly.

Summary

  • JDBC connects Java to databases like MySQL.
  • Get a Connection with the URL, user and password.
  • Use a PreparedStatement with ? placeholders for queries.
  • Read a SELECT's rows from a ResultSet with rs.next().
  • Always close resources and use placeholders to prevent SQL injection.

Next, design the database tables in MySQL data types, or secure queries with keys and constraints.

Frequently Asked Questions

What is JDBC in Java?
JDBC (Java Database Connectivity) is the standard API for connecting Java programs to databases like MySQL. It lets you open a connection, run SQL queries, and read the results, all from Java code.
How do I connect Java to a MySQL database?
Add the MySQL JDBC driver, then use DriverManager.getConnection(url, user, password) with a URL like jdbc:mysql://localhost:3306/dbname. This returns a Connection you use to run queries.
What is a PreparedStatement and why use it?
A PreparedStatement is a precompiled SQL statement with placeholders (?) for values. It prevents SQL injection by treating input as data, not code, and it is also faster for repeated queries. Prefer it over Statement.
What is a ResultSet?
A ResultSet holds the rows returned by a SELECT query. You loop through it with while (rs.next()) and read each column with methods like rs.getString("name") or rs.getInt("age").
How do I prevent SQL injection in JDBC?
Always use a PreparedStatement with ? placeholders and set values with methods like setString. Never build SQL by joining strings with user input, which is what allows injection attacks.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicSecond Largest in Array Your progress: 57 / 61 (93%) · Lesson 58 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free