Mark As Completed Discussion

Executing Queries

To perform basic database operations using JDBC, we can execute queries to retrieve data from the database.

Here's an example of executing a simple SELECT query using JDBC:

TEXT/X-JAVA
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.ResultSet;
4import java.sql.Statement;
5
6public class Main {
7    public static void main(String[] args) {
8        // Replace with your database URL, username, and password
9        String url = "jdbc:mysql://localhost:3306/mydatabase";
10        String username = "root";
11        String password = "password";
12
13        try {
14            // Establish a connection to the database
15            Connection connection = DriverManager.getConnection(url, username, password);
16
17            // Create a statement
18            Statement statement = connection.createStatement();
19
20            // Execute a query
21            String query = "SELECT * FROM users";
22            ResultSet resultSet = statement.executeQuery(query);
23
24            // Process the result set
25            while (resultSet.next()) {
26                int id = resultSet.getInt("id");
27                String name = resultSet.getString("name");
28                String email = resultSet.getString("email");
29
30                // Print the data
31                System.out.println("ID: " + id);
32                System.out.println("Name: " + name);
33                System.out.println("Email: " + email);
34                System.out.println();
35            }
36
37            // Close the connection
38            connection.close();
39        } catch (Exception e) {
40            System.out.println("Error executing query: " + e.getMessage());
41        }
42    }
43}

In this example, we establish a connection to the database using the specified URL, username, and password. We then create a Statement object and execute a SELECT query to retrieve all records from the users table.

We process the result set by iterating over the rows using the next() method. For each row, we retrieve the column values using the appropriate getter methods (e.g., getInt(), getString()), and print them to the console.

Finally, we close the connection to release any resources used.

Executing queries is the foundation for performing various database operations using JDBC. By using different types of queries (SELECT, INSERT, UPDATE, DELETE), we can interact with the database and manipulate data as needed.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment