How to retrieve data from a database using Java?

In Java, you can retrieve data from a database using JDBC (Java Database Connectivity) technology. Here is a simple example code:

import java.sql.*;

public class DatabaseApp {

    public static void main(String[] args) {

        Connection conn = null;

        Statement stmt = null;

        ResultSet rs = null;

        try {

            // 连接数据库

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",

             "username", "password");

            // 创建Statement对象

            stmt = conn.createStatement();

            // 执行查询语句

            String sql = "SELECT * FROM mytable";

            rs = stmt.executeQuery(sql);

            // 处理结果集

            while (rs.next()) {

                int id = rs.getInt("id");

                String name = rs.getString("name");

                int age = rs.getInt("age");

                System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);

            }

        } catch (SQLException e) {

            e.printStackTrace();

        } finally {

            // 关闭数据库连接

            try {

                if (rs != null) {

                    rs.close();

                }

                if (stmt != null) {

                    stmt.close();

                }

                if (conn != null) {

                    conn.close();

                }

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

    }

}

The code above begins by establishing a connection to the database using the `DriverManager.getConnection` method, then creates a `Statement` object for executing SQL statements. To execute a query, the `executeQuery` method can be used, and the results can be retrieved through a `ResultSet` object. Finally, each row of data is extracted and processed within a `while` loop. It is important to remember to call the `close` method to close the database connection, Statement object, and ResultSet object after using them to release resources and avoid memory leaks.

bannerAds