본문 바로가기

Java

[JDBC] 자바에서 sql문 처리하기 (Statement)

이번 주제에서 알아볼 것은 Java에서 SQL을 처리하는 방법을 알아보겠습니다.


Statement (java.sql.Statement)는 Connection으로 연결한 객체에게, Query 작업을 실행하기 위한 객체.

 - 정적인 쿼리를 처리할 수 있다.
 - 즉 쿼리를 처리할 때는 반드시 값이 미리 입력되어야만 처리가 가능하다.

먼저 볼것은 Statement를 생성하고 사용하는 방법
Statement객체를 생성하기 위해서는 Connection이 먼저 연결되야 한다.

연결하는 방법은 https://aricode.tistory.com/8에서 확인하면 된다!

 

package jdbc;

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

public class DBConnection {

	private Connection con;
	private Statement stmt;

	public DBConnection() {
		try {
			String url = "jdbc:mysql://localhost/?characterEncoding=UTF-8&serverTimezone=UTC";
			String user = "user";
			String passwd = "1234";

			con = DriverManager.getConnection(url, user, passwd);
			System.out.println("DB연결 성공");

			stmt = con.createStatement();
			System.out.println("Statement객체 생성 성공");

			stmt.close();
			con.close();

		} catch (SQLException e) {
			System.out.println("DB연결 실패");
			System.out.print("사유 : " + e.getMessage());
		}
	}

	public static void main(String[] args) {
		new DBConnection();
	}

}


Connection을 연결했으면 'Statement stmt = con.createStatement();'문을 통해 Statement객체를 생성할 수 있습니다.

이제 쿼리문을 처리하는 방법은 알려드리겠습니다.
executeUpdate()executeQuery() 메소드가 있습니다.

각각의 메소드는 조금씩 다른 역할을 수행합니다.

 - executeUpdate(String sql)

조회문(select, show 등)을 제외한 create, drop, insert, delete, update 등등 문을 처리할 때 사용한다.

예시) executeUpdate("drop table Example");

 

package jdbc;

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

public class DBConnection {

	private Connection con;
	private Statement stmt;

	public DBConnection() {
		try {
			// ...생략...
            
			stmt = con.createStatement();
			System.out.println("Statement객체 생성 성공");
			
			stmt.executeUpdate("use coffee"); //coffee라는 데이터 베이스에 접속
			stmt.executeUpdate("drop table if exists Example"); //Example 이라는 테이블이 있을 경우 삭제
			System.out.println("Example 테이블을 정상적으로 삭제했습니다.");
			
			stmt.close();
			con.close();

		} catch (SQLException e) {
			System.out.println("DB연결 실패하거나, SQL문이 틀렸습니다.");
			System.out.print("사유 : " + e.getMessage());
		}
	}

	public static void main(String[] args) {
		new DBConnection();
	}

}


그리고 쿼리문을 처리하면 int값을 반환한다.

 

 - executeQuery(String sql)

조회문(select, show 등)을 실행할 목적으로 사용한다.

예시) executeQuery("select * from Example");

 

package jdbc;

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

public class DBConnection {

	private Connection con;
	private Statement stmt;

	public DBConnection() {
		try {
			//...생략...
            
			stmt = con.createStatement();
			System.out.println("Statement객체 생성 성공");
			
			stmt.executeUpdate("use coffee"); //coffee라는 데이터 베이스에 접속
			stmt.executeQuery("select * from Example"); //Example 테이블을 조회
			System.out.println("Example 테이블을 조회했습니다.");
			
			stmt.close();
			con.close();

		} catch (SQLException e) {
			System.out.println("DB연결 실패하거나, SQL문이 틀렸습니다.");
			System.out.print("사유 : " + e.getMessage());
		}
	}

	public static void main(String[] args) {
		new DBConnection();
	}

}

 

쿼리문을 처리한 후, ResultSet객체를 반환한다.

- 여기서 ResultSet이란, 조회된 목록들의 저장된 객체를 반환했다고 생각하고 넘어가겠습니다.

 

Statement 보다 편하고, 앞으로 자주 볼 PreparedStatement가 있습니다.

이 내용은 다음번에 소개 하도록 하고, 다음 내용은 ResultSet의 대한 글이 있겠습니다.

 

여담으로 요새 일이 좀 있어서 글을 많이 못 작성했어요.. 다음부터는 1달에 1번 이상은 글을 쓰겠습니다~
그리고 요새 코로나가 유행하면서 많이 힘드실 텐데 마스크 잘 쓰시고 건강하게 보내세요!