Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

Java에서 MySQL SELECT 쿼리에 PreparedStatement를 사용하는 방법

Java에서 MySQL 데이터베이스의 SELECT 쿼리를 실행하려면 PreparedStatement 객체의 executeQuery() 메서드를 사용해야 합니다. 기본적인 사용 문법은 다음과 같습니다.

yourPreparedStatementObject = yourConnectionObject.prepareStatement(yourQueryName);
yourResultSetObject = yourPreparedStatementObject.executeQuery();

1. 샘플 테이블 생성하기

먼저 'sample' 데이터베이스에 실습용 테이블을 생성합니다. 테이블 생성 쿼리는 다음과 같습니다.

mysql> create table JavaPreparedStatement
-> (
-> Id int,
-> Name varchar(10),
-> Age int
-> );
Query OK, 0 rows affected (0.89 sec)

2. 샘플 데이터 삽입하기

INSERT 명령어를 사용해 테이블에 레코드를 여러 개 삽입합니다.

mysql> insert into JavaPreparedStatement values(1,'Larry',23);
Query OK, 1 row affected (0.16 sec)
mysql> insert into JavaPreparedStatement values(2,'Sam',25);
Query OK, 1 row affected (0.21 sec)
mysql> insert into JavaPreparedStatement values(3,'Mike',26);
Query OK, 1 row affected (0.12 sec)

3. Java 코드로 전체 레코드 조회하기

이제 Java의 PreparedStatement를 사용해 테이블의 모든 레코드를 조회할 수 있습니다. 이때 반드시 executeQuery() 메서드를 사용해야 하며, 이 메서드는 조회 결과를 담고 있는 ResultSet 객체를 반환합니다.

다음은 전체 Java 코드입니다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class PreparedStatementSelectQueryDemo {
    public static void main(String[] args) {
        String JdbcURL = "jdbc:mysql://localhost:3306/sample?useSSL=false";
        String Username = "root";
        String password = "123456";
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rst = null;
        String myQuery = "select Id,Name,Age from JavaPreparedStatement";
        try {
            con = DriverManager.getConnection(JdbcURL, Username, password);
            pstmt = con.prepareStatement(myQuery);
            rst = pstmt.executeQuery();
            System.out.println("Id\t\tName\t\tAge\n");
            while(rst.next()) {
                System.out.print(rst.getInt(1));
                System.out.print("\t\t"+rst.getString(2));
                System.out.print("\t\t"+rst.getInt(3));
                System.out.println();
            }
        } catch(Exception exec) {
            exec.printStackTrace();
        }
    }
}

실행 결과 확인

위 코드를 실행하면 JDBC URL을 통해 'sample' 데이터베이스에 연결된 후, prepareStatement()로 쿼리를 준비하고 executeQuery()를 호출해 결과를 가져옵니다. while 루프 안에서 next() 메서드를 호출해 ResultSet의 각 행을 순차적으로 읽어 화면에 출력합니다.

정상적으로 실행되면 다음과 같은 형태의 출력 결과를 확인할 수 있습니다.

Id     Name     Age

1      Larry    23
2      Sam      25
3      Mike     26

참고: PreparedStatement를 사용하는 이유

PreparedStatement는 단순히 Statement를 대체하는 것 이상의 장점을 제공합니다. 첫째, SQL 인젝션 공격을 효과적으로 방지할 수 있고, 둘째, 쿼리가 미리 컴파일되어 동일한 쿼리를 반복 실행할 때 성능이 향상됩니다. 셋째, '?' 플레이스홀더를 통한 파라미터 바인딩으로 코드의 가독성과 유지보수성이 크게 개선됩니다.