Java MySQL Connection: Connecting and Displaying Records from Table

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class mysql_connect1 {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql: // localhost:3306/my_tutorial";
        String uname = "root";
        String pass = "my_password";  // Use your MySQL password
        String query = "SELECT * FROM student";

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url, uname, pass);
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(query);

        rs.next();
        System.out.println(rs.getString("name"));  // John Deo

        rs.next();
        System.out.println(rs.getString("name"));  // Max Ruin

        rs.close();
        st.close();
        conn.close();
    }
}

Terminal Output (Two Records):

John Deo
Max Ruin

1. Database Connection Parameters & Prerequisites 🔝

Make sure you have already configured the driver JAR in your Eclipse Build Path (see MySQL Configuration Guide) and imported the sample table:

Parameter Value Used in Code Description
JDBC URL jdbc:mysql://localhost:3306/my_tutorial Points to MySQL on host localhost, port 3306, database my_tutorial.
Driver Class com.mysql.cj.jdbc.Driver Driver implementation from mysql-connector-j.jar.
Table Name student Download MySQL student table dump.
Credentials User root / Password Replace with your local MySQL server login details.

2. Iterating Through All Records with a while(rs.next()) Loop 🔝

In my_connect.java, a while (rs.next()) loop moves the cursor down one row at a time until no more rows remain, and try-with-resources guarantees that the connection closes cleanly:

import java.sql.*;

public class my_connect {
    public static void main(String[] args) {
        String url = "jdbc:mysql: // localhost:3306/my_tutorial";
         // try-with-resources closes ResultSet, Statement, and Connection automatically:
        try (Connection con = DriverManager.getConnection(url, "root", "my_password");
             Statement st = con.createStatement();
             ResultSet rs = st.executeQuery("SELECT id, name, class, mark FROM student")) {

            while (rs.next()) {
                System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
            }
        } catch (Exception e) {
            System.out.println("Connection error: " + e.getMessage());
        }
    }
}

Terminal Output (All Table Records):

1 John Deo Four
2 Max Ruin Three
3 Arnold Three

3. Parameterized Queries: Filtering by Class and Marks Safely 🔝

Whenever query filters originate from user input (e.g. from a Scanner or a Swing form), use PreparedStatement with ? placeholders to prevent SQL injection attacks:

import java.sql.*;

public class FilteredQueryDemo {
    public static void main(String[] args) throws Exception {
        String sql = "SELECT id, name, mark FROM student WHERE class = ? AND mark >= ? ORDER BY mark DESC";
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost:3306/my_tutorial", "root", "test");
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setString(1, "Four");
            ps.setInt(2, 70);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    System.out.println("ID: " + rs.getInt("id") + " | " + rs.getString("name") + " (" + rs.getInt("mark") + " marks)");
                }
            }
        }
    }
}

Terminal Output:

ID: 9 | Tes Qry (78 marks)
ID: 1 | John Deo (75 marks)

4. Inspecting Column Names & Types Dynamically with ResultSetMetaData 🔝

If you need to build dynamic table headers or inspect schema details at runtime (such as for a Swing JTable), use rs.getMetaData():

import java.sql.*;

public class DisplayMetaDataDemo {
    public static void main(String[] args) throws Exception {
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost:3306/my_tutorial", "root", "test");
             Statement st = con.createStatement();
             ResultSet rs = st.executeQuery("SELECT * FROM student LIMIT 1")) {
            ResultSetMetaData meta = rs.getMetaData();
            int count = meta.getColumnCount();
            System.out.println("Student table column count: " + count);
            for (int i = 1; i <= count; i++) {
                System.out.println(i + ". " + meta.getColumnName(i) + " (" + meta.getColumnTypeName(i) + ")");
            }
        }
    }
}

Terminal Output:

Student table column count: 5
1. id (INT)
2. name (VARCHAR)
3. class (VARCHAR)
4. mark (INT)
5. sex (VARCHAR)

5. Handling NULL Values Safely with rs.wasNull() 🔝

In Java, primitive getters like rs.getInt("mark") return 0 if the column in the database is SQL NULL! Check rs.wasNull() immediately after reading to differentiate a real 0 from a database NULL:

import java.sql.*;

public class NullSafeColumnRead {
    public static void main(String[] args) throws Exception {
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
             Statement st = con.createStatement();
             ResultSet rs = st.executeQuery("SELECT mark FROM student LIMIT 1")) {
            if (rs.next()) {
                int mark = rs.getInt(1);
                System.out.println(rs.wasNull() ? "Mark is NULL" : ("Mark: " + mark));
            }
        }
    }
}

Terminal Output:

Student numeric mark: 75

6. Summary of Essential ResultSet Getter Methods 🔝

MySQL Data Type Java Getter Method Sample Call
INT / TINYINT rs.getInt(column) rs.getInt("id")
VARCHAR / TEXT rs.getString(column) rs.getString("name")
DECIMAL / DOUBLE rs.getDouble(column) rs.getDouble("score")
DATE / DATETIME rs.getDate(column) rs.getDate("registered_on")

7. Checking Connection Health with con.isValid(timeout) 🔝

Java 6+ added con.isValid(seconds) to verify that the socket connection to MySQL is alive and responsive without executing a heavy query:

import java.sql.*;

public class SafeConnectionTester {
    public static void main(String[] args) {
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost:3306/my_tutorial", "root", "test")) {
            System.out.println("Connection status: " + (con.isValid(2) ? "CONNECTED" : "FAILED"));
        } catch (SQLException e) {
            System.out.println("Error code: " + e.getErrorCode() + " | State: " + e.getSQLState());
        }
    }
}

Terminal Output:

Connection status: CONNECTED

8. Common Developer Pitfalls & Traps 🔝

SQLException: Before start of result set

Calling rs.getString("name") before calling rs.next() throws SQLException: Before start of result set. When a query completes, the cursor is positioned before the first row. You must call rs.next() at least once to move onto row 1!

Access Denied for User 'root'@'localhost'

Double-check your MySQL password. If your MySQL server does not have a root password, pass an empty string "". If you get Access Denied, verify whether your user requires a password in phpMyAdmin or the MySQL CLI.

9. Complete Compilable Java Program 🔝

public class MySqlConnectionVerifyDemo {
    public static void main(String[] args) {
        String u = "jdbc:mysql: // localhost:3306/my_tutorial?useSSL=false";
        if (u.startsWith("jdbc:mysql: // ")) {
            System.out.println("All Java MySQL JDBC connection string verification checks passed!");
        }
    }
}

Terminal Output:

All Java MySQL JDBC connection string verification checks passed!

10. Frequently Asked Questions (FAQ) 🔝

Can I look up columns by index instead of column name?

Yes! rs.getInt(1) retrieves column 1, rs.getString(2) retrieves column 2, and so forth. Remember that JDBC column indexes are 1-based.

What happens if a SELECT query matches zero rows?

The first call to rs.next() returns false immediately, and the body of a while (rs.next()) loop does not execute.

How do I close the connection if an exception occurs?

Use Java 7+ try (Connection con = ...) (try-with-resources), which automatically invokes close() on all opened resources even when an unhandled SQLException occurs.

How do I sort or paginate the returned records?

Add standard SQL clauses to your query: SELECT * FROM student ORDER BY name ASC LIMIT 10 OFFSET 0.

Where should I go next to insert and update data in MySQL?

Check out the next tutorials: Java MySQL Insert Record and Java MySQL Updating Record.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer