Select Records
In this tutorial, we are going to discuss about how to select records from table using JDBC. Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.
Here’s a simple example of select records using JDBC (Java Database Connectivity). In this example, I’ll demonstrate how to connect to a MySQL database and select records from the table named “employees” with three columns: “id”, “name”, and “salary”.
To retrieve records from a table using JDBC, you typically execute a SQL SELECT
statement. Here’s an example demonstrating how to select records using JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SelectExample {
public static void main(String[] args) {
// JDBC URL, username, and password for your database
String url = "jdbc:mysql://localhost:3306/employee";
String user = "ashok";
String password = "Ashok@123";
// SQL SELECT statement
String selectSQL = "SELECT * FROM employee WHERE condition";
try (
// Establishing connection to the database
Connection connection = DriverManager.getConnection(url, user, password);
// Creating a prepared statement
PreparedStatement preparedStatement = connection.prepareStatement(selectSQL)
) {
// Executing the SELECT statement
try (ResultSet resultSet = preparedStatement.executeQuery()) {
// Iterating through the result set
while (resultSet.next()) {
// Retrieve data from each row
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String salary = resultSet.getString("salary");
// Do something with the retrieved data, such as printing it
System.out.println("ID: " + id + ", name: " + name + ", Salary: " + salary);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Replace "employee"
, "ashok"
, "Ashok@143"
, "employee"
, "id"
, "name"
, and "salary"
with your actual database name, username, password, table name, and column names respectively.
Ensure that:
- You have the appropriate permissions to select records from the table in the database.
- Handle exceptions properly, especially when dealing with database operations. In this example, exceptions are simply printed, but in a real application, you would handle them more robustly, possibly logging them or presenting meaningful error messages to the user.
- Close the resources (
ResultSet
,PreparedStatement
, andConnection
) properly after using them to release database resources. Here, I’ve used try-with-resources to ensure proper resource management.
That’s all about the how to select records from table using JDBC. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!