이번 시간에는 Spring DB 연동 과정에서 발생할 수 있는 익셉션에 대해서 알아보겠습니다.
SQLException
DB 연결 정보가 올바르지 않으면 나타나는 익셉션입니다. DB 연결 정보는 DataSource에 있으므로 DataSource를 잘못 설정하면 연결을 구할 수 없다는 익셉션(CannotGetJdbcConnecdtionException)이 발생합니다.
예를 들어, 데이터베이스 암호를 잘못 설정하여 나타는 메시지는 다음과 같습니다.
CannotGetJdbcConnection: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'spring5'@'localhost'(using passsword:YES)
CommunicationsException
또한, DB를 실행하지 않았거나 방화벽에 막혀 있어, DB에 연결할 수 없다면 연결 자체를 할 수 없다는 에러 메시지가 출력됩니다.
이 메시지는 MySQL JDBC 드라이버 버전에 따라 일부 메시지가 다를 수 있습니다.
CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
로컬에 설치된 DBMS를 이용해서 테스트할 때 이런 에러가 발생하는 이유는 주로 DBMS를 실행하지 않았기 때문이므로 DBMS를 실행했는지 확인해 보면 됩니다.
BadSqlGrammarException
잘못된 쿼리를 사용하는 것도 주요 에러 원인이 될 수 있습니다.
jdbcTemplate.update("update MEMBER set NAME = ?, PASSWORD = ? where" +
"EMAIL =?", member.getName(), member.getPassword(), member.getEmail());
이 코드가 실행되면 아래와 같은 쿼리로 실행 됩니다.
update MEMBER set NAME = ?, PASSWORD = ? whereEMAIL = ?
쿼리를 보시면 where 뒤에 존재해야 하는 공백문자가 없습니다. 문자열을 연결할 때 줄이 바뀌는 부분에서 실수로 공백문자를 누락하면 다음과 유사한 익셉션이 발생합니다.
Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select * from MEMBER whereEMAIL = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= 'madvirus@madvirus.net'' at line 1
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1402)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:620)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:657)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:688)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:756)
at spring.MemberDao.selectByEmail(MemberDao.java:27)
at main.MainForMemberDao.updateMember(MainForMemberDao.java:45)
at main.MainForMemberDao.main(MainForMemberDao.java:25)
지금까지 DB 연동과정에서 발생하는 세 가지 종류의 익셉션에 대해 살펴보았습니다. 이외에도 여러 메시지를 보면 문제 발생 원인을 찾는 데 도움이 됩니다. DB 연동 코드를 실행하는 과정에서 익셉션이 발생하면 당황하지 말고 익셉션 메시지를 차분히 살펴보는 습관을 들이도록 합시다.
'Spring' 카테고리의 다른 글
[Spring] Spring DB 트랜잭션 처리 (1) | 2024.02.28 |
---|---|
[Spring] Spring DB - 익셉션 변환처리 (0) | 2024.02.27 |
[Spring] Spring DB - 쿼리 실행 테스트 (1) | 2024.02.25 |
[Spring] Spring DB - 쿼리실행 (0) | 2024.02.21 |
[Spring] Spring JdbcTemplate - qureyForObject 메서드 (0) | 2024.02.19 |