JavaScript, UserDao

calis_ws·2023년 5월 23일
0

JavaScript

  1. 문법이 쉽고 직관적이다.
  2. FE, BE 등등 활용할 수 있는 범위가 매우 넓다.
  3. 웬만한 구현은 찾아보면 쉽게 구현할 수 있다.

세미콜론(;)

Js는 세미콜론을 지우거나 줄을 바꾸는 것으로 각각의 명령어 인식

변수 선언

  • var 변수명 = 값;
  • let 변수명 = 값;
  • const 변수명 = 값;

자료형

  • 문자열 (String) → ‘ ’ 또는 “ ” 사용
  • 숫자 (int, float) → 정수형(int), 실수형(float)
  • 불(bool) → true, false
    데이터 앞쪽에 typeof 를 붙이면(typeof 데이터) 결과로 그 데이터의 자료형이 나온다.

로또 번호 추첨기

...
<body>
    <h1>로또 번호 추첨기</h1>
    <script>
        var lotto = [];
        for (var i = 0; i < 6; i++){
			var num = parseInt(Math.random() * 45 + 1);
			// num 값이 있으면 위치, 없으면 -1
			if (lotto.indexOf(num) == -1) {
				lotto.push();
			}
        }
		lotto.sort((a, b) => a - b);	// 오름차순 정렬
        document.write(lotto);
    </script>
</body>
  ...

자소서 글자수 계산기

<textarea class="form-control" rows="3" id="jasoseol" onkeydown="counter();">저는 인성 문제가 없습니다.</textarea> // 이벤트 = 이벤트핸들링
    <span id="count">(0/200)</span>
    <script>
        function counter() {							// 함수 선언
            var content = document.getElementById('jasoseol').value;	// document 메소드
            if (content.length > 200) {
                content = content.substring(0,200);		// 200자 이후로 자른다.
                document.getElementById('jasoseol').value = content;
            }
            document.getElementById('count').innerHTML = '(' + content.length + '/200)';
        }
        counter();
    </script>

미니 스타크래프트

 <script>
 	var hp = 3; // hp 변수에 3넣음
    $('#drone').click(function() { // drone 이미지를 선택하고 , .click Event 받음
        $('#spit').fadeIn();       // 숨김 처리된 spit을 나타나게 함.
        $('#spit').animate({'left': '+=250px'}); // 왼쪽에서 250만큼 이동
        $('#spit').fadeOut(function(){   // bunker에 맞은 spit이 사라지는 익명함수
            hp = hp - 1;               
            $('#hp').text('HP: ' + hp);
            if (hp == 0) {           // hp == 0 이면 bunker 사라짐
                $('#bunker').fadeOut();
            }
        });
        $('#spit').css({left: 150});  // 사라진 spit 원위치
    });
</script>

기념일 계산기

<script>
        var now = new Date();
        var start = new Date('2020-06-30');

        //우리 몇 일째?
        var timeDiff = now.getTime() - start.getTime();
        var day = Math.floor(timeDiff / (1000 * 60 * 60 * 24) + 1);
        $('#love').text(day + '일째');

        //기념일까지 남은 날짜는?
        var valentine = new Date('2021-02-14');
        var timeDiff2 = valentine.getTime() - now.getTime();
        var day2 = Math.floor(timeDiff2 / (1000 * 60 * 60 * 24) + 1);
        $('#valentine').text(day2 + '일 남음');

        //천일은 언제인가?
        var thousand = new Date(start.getTime() + 999 * (1000 * 60 * 60 * 24));
        var thousandDate = thousand.getFullYear() + '.' + (thousand.getMonth()+1) + '.' + thousand.getDate();
        $('#thousand-date').text(thousandDate);

        //기념일까지 남은 날짜는?
        var timeDiff3 = thousand.getTime() - now.getTime();
        var day3 = Math.floor(timeDiff3 / (1000 * 60 * 60 * 24) + 1);
        $('#thousand').text(day3 + '일 남음');
    </script>

UserDao 클래스

dao package 생성과 UserDao 클래스 생성

domain package 생성과 User 클래스 생성

users 테이블 생성

User Class

public class User {
    private String id;
    private String name;
    private String password;

    public String getId() { 			// getter
        return id;
    }

    public void setId(String id) {		// setter
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

UserDao Class

DAO(Data Access Object) : 데이터를 연결하는 오브젝트

import com.example.tobyspring3.domain.User;

import java.sql.*;
import java.util.Map;

import static java.lang.System.getenv;

public class UserDao {

    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Map<String, String> env = getenv();                     // Connection 의 분리
        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
        );
        return conn;
    }
    public void add(User user) throws ClassNotFoundException, SQLException {
        Connection conn = getConnection();

        PreparedStatement pstmt = conn.prepareStatement("insert into users(id, name, password) values(?, ?, ?)");
        pstmt.setString(1, user.getId());
        pstmt.setString(2, user.getName());
        pstmt.setString(3, user.getPassword());

        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    }

    public User get(String id) throws ClassNotFoundException, SQLException {
        Connection conn = getConnection();

        PreparedStatement pstmt = conn.prepareStatement("select id, name ,password from users where id = ?");
        pstmt.setString(1, id);
        ResultSet rs = pstmt.executeQuery();
        rs.next(); // ctrl + enter

        User user = new User();
        user.setId(rs.getString("id"));
        user.setName(rs.getString("name"));
        user.setPassword(rs.getString("password"));

        pstmt.close();
        conn.close();

        return user;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        UserDao userDao = new UserDao();
        User user = new User();
        user.setId("3");
        user.setName("kyeongrok");
        user.setPassword("5678");
        userDao.add(user);

        User selectedUser = userDao.get("3");
        System.out.println(selectedUser.getId());
        System.out.println(selectedUser.getName());
        System.out.println(selectedUser.getPassword());
    }
}
  • resultset, pstmt, conn 순으로 close 해야 한다.

자주 나는 에러

  • DB_HOST 입력 할 때 jdbc:mysql:// 를 안 쓰는 경우

  • Edit Configuration 을 올바르게 작성하지 않은 경우

  • n번 id가 이미 등록되어 있는 경우

  • 환경변수를 올바르게 작성하지 않은 경우

인사이트 타임

알파벳 찾기

https://www.acmicpc.net/problem/10809
16:15 ~ 16:40

어려워서 풀이 실패

20:45 ~ 21:10 재도전

import java.util.Scanner;

public class findAlpabet {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[26];
        String str = sc.next();

        for (int i = 0; i < arr.length; i++) {
            arr[i] = -1;
        }

        for (int i = 0; i < str.length(); i++) {
            if (arr[str.charAt(i) - 'a'] == -1) {
                arr[str.charAt(i) - 'a'] = i;
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.printf("%d ", arr[i]);
        }
    }
}


겨우 정답을 받아냈다.

태환님의 열렬한 피드백으로 해결에 큰 도움을 얻었다.
인덱스의 로직을 겨우겨우 이해한 돌머리였지만 출력하는 과정에서 시간을 더 쓰게 되었다.
태환님 감사합니다.

review

오전에는 JS강의를 수강했는데 어제는 이두희 대표님이 강의하시더니 오늘은 조코딩님이 갑자기 등장해서 놀랐다. 유튜브를 가끔 보는 편인데 멋사에서도 보니 반가웠다. 할튼 반가움은 잠깐이고 JS는 아예 처음이었는데 그렇게 어려운건 아니지만 그렇다고 쉬운 언어는 아닌 느낌?
강의가 비디팅 코딩이라 중간중간 실습시간이 있는데 처음보는 코드라 계속 앞으로 돌려서 보게 되었다. 그나마 미니 스타크래프트 시간이 재밌었다.

오후에는 오늘도 역시 할만한 Spring DB시간. 의외로 에러가 안나서 쉽게 진행할 수 있어서 만족스러웠다. 나중가면 또 난이도가 급격하게 수직상승할까봐 걱정이 된다. 아직 초반이라서 다행인듯 싶다.

인사이트탐 때 알고리즘 문제 풀다가 모르겠어서 던져버리고 피드백시간에 이해해야겠다 했는데 설명을 듣고도 도저히 이해가 안가서 미칠뻔했다. 이런 스톤헤드를 태환님이 끝까지 붙잡고 설명해주신 덕분에 겨우 이해할 수 있었는데 아 난 왤케 알고리즘이 X같을까? 다 좋은데 알고리즘만 없었으면 좋겠다. 어쨌든 해결은 했으니 오늘도 수고했다.

profile
반갑습니다람지

0개의 댓글