次に、JDBCステートメントを使用してテーブルからレコード全体を選択し、ResultSetオブジェクトを介してすべてのレコードを表示する方法を示す例を示します。 selectクエリを発行するには、次のように `Statement.executeQuery`メソッドを呼び出します。

String selectTableSQL = "SELECT USER__ID, USERNAME from DBUSER";
Statement statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectTableSQL);
while (rs.next()) {
    String userid = rs.getString("USER__ID");
    String username = rs.getString("USERNAME");
}


完全な例…​

package com.mkyong.jdbc;

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

public class JDBCStatementSelectExample {

    private static final String DB__DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DB__CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
    private static final String DB__USER = "user";
    private static final String DB__PASSWORD = "password";

    public static void main(String[]argv) {

        try {

            selectRecordsFromDbUserTable();

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

    }

    private static void selectRecordsFromDbUserTable() throws SQLException {

        Connection dbConnection = null;
        Statement statement = null;

        String selectTableSQL = "SELECT USER__ID, USERNAME from DBUSER";

        try {
            dbConnection = getDBConnection();
            statement = dbConnection.createStatement();

            System.out.println(selectTableSQL);

           //execute select SQL stetement
            ResultSet rs = statement.executeQuery(selectTableSQL);

            while (rs.next()) {

                String userid = rs.getString("USER__ID");
                String username = rs.getString("USERNAME");

                System.out.println("userid : " + userid);
                System.out.println("username : " + username);

            }

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        } finally {

            if (statement != null) {
                statement.close();
            }

            if (dbConnection != null) {
                dbConnection.close();
            }

        }

    }

    private static Connection getDBConnection() {

        Connection dbConnection = null;

        try {

            Class.forName(DB__DRIVER);

        } catch (ClassNotFoundException e) {

            System.out.println(e.getMessage());

        }

        try {

            dbConnection = DriverManager.getConnection(DB__CONNECTION, DB__USER,
                    DB__PASSWORD);
            return dbConnection;

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

        return dbConnection;

    }

}

結果

レコードのリストがテーブル “DBUSER”から検索され、表示されます。


jdbc


select

リンク://タグ/ステートメント/[ステートメント]