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
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. |
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
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)
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)
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
| 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") |
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
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!
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.
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!
Yes! rs.getInt(1) retrieves column 1, rs.getString(2) retrieves column 2, and so forth. Remember that JDBC column indexes are 1-based.
The first call to rs.next() returns false immediately, and the body of a while (rs.next()) loop does not execute.
Use Java 7+ try (Connection con = ...) (try-with-resources), which automatically invokes close() on all opened resources even when an unhandled SQLException occurs.
Add standard SQL clauses to your query: SELECT * FROM student ORDER BY name ASC LIMIT 10 OFFSET 0.
Check out the next tutorials: Java MySQL Insert Record and Java MySQL Updating Record.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.