Database

[ JDBC ] Insert , select 하기

walwal_ 2023. 5. 26. 17:48

 

 

 

 

 

앞 글에서 IntelliJ와 DB 를 연결하고, 환경변수를 통해 DB정보를 추가 해주었다.

 

환경변수를 이용해 Insert , select 를 해보자

 

 

 

테이블 생성



쿼리 콘솔에 아래 쿼리문을 붙혀넣고 실행하면 테이블이 생성된다.

 

create table user(
    id int primary key ,
    name varchar(20) not null ,
    password varchar(10) not null
);

 

 

 

 

 


 

 

 

Connection 메소드 만들기




 

UserDao 클래스를 만들고 앞 글에서 설정해줬던 환경변수 name(DB_HOST, DB_USER, DB_PASSWORD)을 이용해

Connection하기

(참고) 환경변수를 사용할 클래스와 변수 이름을 신경쓰기

public class UserDao {
	private static Connection getConnection() throws ClassNotFoundException, SQLException{
		
		Map<String, String> env = getenv() // getenv() 는 환경변수를 가져오는 내 메서드임
		String dbHost = env.get("DB_HOST");
		String dbUser = env.get("DB_USER");
		String dbPassword = env.get("DB_PASSWORD");
	
		Class.forName("com.mysql.cj.jdbc.Driver");
	
		Connection conn = DriverManager.getConnection(dbHost, dbUser, dbPassword);// 가져온 환경변수 connection하기
		return conn;
	}
}

 

 

 

 

테이블에 값 추가하기

 

 

 

 

public class UserDao {


	public void add(User user) throws ClassNotFoundException, SQLException {
        Connection conn = getConnection(); // 커넥션 얻기
					
   		 // 쿼리문 작성
        PreparedStatement pstmt = conn.prepareStatement("insert into user(id, name, password) values(?, ?, ?)");

        //매개변수로 들어온 user변수에서 id, name, password 가져오기
        pstmt.setString(1,user.getId());
        pstmt.setString(2,user.getName());
        pstmt.setString(3,user.getPassword());

        // 쿼리문 업데이트하기
        pstmt.executeUpdate();
        close(conn, pstmt);
    }
    
    
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        UserDao userDao = new UserDao(); 
        User user = new User(); 
        user.setId("3");
        user.setName("삼삼");
        user.setPassword("3333");
        userDao.add(user);  // add 메소드에 id,name,password 를 set 하고, user객체를 넘김
    }
}

 

결과

 

 

 

 

 

 

 

select 하고 출력하기





public class UserDao {
	public User get(String id) throws ClassNotFoundException, SQLException {
        Connection conn = getConnection();// 커넥션 얻기
					
        // 쿼리문 작성
        PreparedStatement pstmt = conn.prepareStatement("select id, name, password from user where id = ? ");
	        
        // 매개변수로 받은 id 를 ? 에 치환
        pstmt.setString(1,id);
        // 쿼리 날리고 반환된 값을 rs 에 저장
        ResultSet rs = pstmt.executeQuery(); 
                //논리적 커서의 위치를 이동시킴
        rs.next();

        //User 클래스 객체 생성 
        User user = new User();

        // rs (pstmt.executeQuery()) 값을 (id, name, password) get으로 꺼내옴
        // 꺼내온 값을 user 객체에 set 함
        user.setId(rs.getString("id"));
        user.setName(rs.getString("name"));
        user.setPassword(rs.getString("password"));
	  
      	rs.close();
        close(conn, pstmt);
	
        // 만들어진 user 객체를 반환함.
        return user;
    }
    
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        UserDao userDao = new UserDao();
        User selectedUser = userDao.get("3");
        System.out.println(selectedUser.getId());
        System.out.println(selectedUser.getName());
        System.out.println(selectedUser.getPassword());
    }
}

결과