DB 7일차 2-1(조건을 주고싶을때)

2022. 12. 15. 11:30코딩배움일지/DataBase

package main.java.com.study.jdbc.main;

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

import main.java.com.study.jdbc.util.DBConnection;

/*board_mst 가 나오게끔 해라.*/
public class jdbcTest2 {

	public static void main(String[] args) {
		Connection connection = DBConnection.getInstance().getConnection();
		
		String sql = "select * from board_mst where writer_id = 1"; /* 조건을 주고 싶을때 where*/
		
		try {
			PreparedStatement pstmt = connection.prepareStatement(sql); 
			ResultSet rs = pstmt.executeQuery();			
			
			while(rs.next()) { 
				System.out.println("id: " + rs.getInt(1) 
				+ "\t title: " + rs.getString(2)
				+ "\t content: " + rs.getString(3)
				+ "\t read_count: " + rs.getInt(4)
				+ "\t writer_id: " + rs.getInt(5));
			}			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
		
}

 

String sql = "select * from board_mst where writer_id = \'junil\'";

문자열 일때

 

String sql = "select * from board_mst where writer_id = ?"; /* 조건을 주고 싶을때 where*/

뭐가 올지 모른다.

 

스캐너 추가

package main.java.com.study.jdbc.main;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

import main.java.com.study.jdbc.util.DBConnection;

/*board_mst 가 나오게끔 해라.*/
public class jdbcTest2 {

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.print("작성자 id: ");
		int writerId = scanner.nextInt();
		
		Connection con = DBConnection.getInstance().getConnection();
		
		String sql = "select * from board_mst where writer_id = ?"; /* 조건을 주고 싶을때 where*/ /*미완성된 초건*/
		PreparedStatement pstmt;
		try {			
			pstmt= con.prepareStatement(sql);
			pstmt.setInt(1, writerId); /*writerId int 로 대체 하겠다*/
			ResultSet rs = pstmt.executeQuery();			
			
			while(rs.next()) { 
				System.out.println("id: " + rs.getInt(1) 
				+ "\t title: " + rs.getString(2)
				+ "\t content: " + rs.getString(3)
				+ "\t read_count: " + rs.getInt(4)
				+ "\t writer_id: " + rs.getInt(5));
			}			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
		
}

결과

작성자 id: 2
데이터베이스 드라이브 로딩 성공!
id: 4	 title: 제목1	 content: 게시글 내용1	 read_count: 0	 writer_id: 2
id: 5	 title: 제목2	 content: 게시글 내용2	 read_count: 0	 writer_id: 2
id: 6	 title: 제목3	 content: 게시글 내용3	 read_count: 0	 writer_id: 2
id: 10	 title: 제목4	 content: 게시글 내용4	 read_count: 0	 writer_id: 2
id: 11	 title: 제목5	 content: 게시글 내용5	 read_count: 0	 writer_id: 2

'코딩배움일지 > DataBase' 카테고리의 다른 글

DB 7일차 (update)  (0) 2022.12.15
DB 7일차(java, sql 연결 insert)  (0) 2022.12.15
DB 7일차 2()  (0) 2022.12.15
DB 7일차(java, sql 연결 select)  (0) 2022.12.15
DB 6일차 4(jdbc)  (0) 2022.12.14