[JDBC] Scanner 이용

혜쿰·2023λ…„ 7μ›” 31일
1

πŸ“Œ ν™œμš©

package pack5db;

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

public class DbTest5 {
	public DbTest5() {
		dbLoading();
		insertDb();
		selectDb();
	}
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private void dbLoading() {
		try {
			Class.forName("org.mariadb.jdbc.Driver");
		} catch (Exception e) {
			System.out.println("λ‘œλ”© μ‹€νŒ¨ :" +e);
			System.exit(0);
		}
	}
	
	private void insertDb() {
		// ν‚€λ³΄λ“œλ‘œ DB에 자료 μž…λ ₯
		try {
			Scanner scanner = new Scanner(System.in);
			conn = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/test","root","λΉ„λ°€λ²ˆν˜Έ");
			
			while(true) {
				System.out.print("code : ");
				String code = scanner.next();
				System.out.print("sang : ");
				String sang = scanner.next();
				System.out.print("su : ");
				String su = scanner.next();
				System.out.print("dan : ");
				String dan = scanner.next();
				// μž…λ ₯ 자료 였λ₯˜ κ²€μ‚¬λŠ” μƒλž΅
				
				pstmt = conn.prepareStatement("insert into sangdata values(?,?,?,?)");
				pstmt.setString(1, code);
				pstmt.setString(2, sang);
				pstmt.setString(3, su);
				pstmt.setString(4, dan);
				pstmt.executeUpdate(); // μΆ”κ°€ μž‘μ—… 진행. λ°˜ν™˜κ°’μ€ μƒλž΅
				System.out.print("κ³„μ†ν• κΉŒμš” (y/n) :");
				String yn = scanner.next();
				// if(yn.equals("n")) break; // while νƒˆμΆœ
				if(yn.equalsIgnoreCase("n")) break; // λŒ€μ†Œλ¬Έμž ꡬ뢄 μ•ˆν•¨		
			}
			scanner.close();
		} catch (Exception e) {
			System.out.println("insertDb err : " +e );
		}finally {
			try {
				if (rs != null) rs.close();
				if (pstmt != null) pstmt.close();
				if (conn != null) conn.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
	
	private void selectDb() {
		// DB에 μž…λ ₯된 자료 읽기
		try {
			conn = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/test","root","λΉ„λ°€λ²ˆν˜Έ");
			
			String sql = "select * from sangdata";
			pstmt = conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			int count = 0;
			System.out.println("μ½”λ“œ\tμƒν’ˆλͺ…\tμˆ˜λŸ‰\t단가");
			while(rs.next()) {
				System.out.println(rs.getString(1) + "\t" +
						rs.getString(2) + "\t" +
						rs.getString(3) + "\t" +
						rs.getString(4));
				count += 1;
			}
			System.out.println("건 수 :" +count + "개");
		} catch (Exception e) {
			System.out.println("selectDb err : " +e );
		}finally {
			try {
				if (rs != null) rs.close();
				if (pstmt != null) pstmt.close();
				if (conn != null) conn.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
		
	
	
	
	public static void main(String[] args) {
		new DbTest5();

	}

}

πŸ“ 좜λ ₯

0개의 λŒ“κΈ€