티스토리 뷰
| JAVA JDBC
Spring에서는 Mybatis를 주로 사용하지만,
JAVA에서 JDBC를 사용할 경우 자주 헷갈리고, 가물가물할 때가 있다..
바로 그 때를 위해!!!
기본적인 내용들을 정리해보려고 한다.
Database는 MySQL를 사용하였다.
|| JDBC 작업 순서
1. Driver Loading (Vendor API)
2. DB 연결 (Connection 생성)
3. SQL 실행 준비
3-1. SQL 작성. (Insert, Update, Delete, Select)
3-2. Statement 생성 (Statement, PreparedStatement)
4. SQL 실행
4-1. Insert, Update, Delete
int x = stmt.execteUpdate(sql);
int x = pstmt.executeUpdate();
4-2. Select
ResultSet rs = pstmt.executeQuery();
rs.next() [단독, if, while]
값얻기 : rs.getString()
rs.getInt()
....
5. DB 연결 종료 : 연결 역순으로 종료, finally
if(rs != null)
rs.close()
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
|| Insert
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | private int insert(JdbcDto jdbcDto) { int cnt = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("insert into jdbctest (id, pwd, name, joindate) \n"); sql.append("values (?, ?, ?, now())"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, jdbcDto.getId()); pstmt.setString(2, jdbcDto.getPwd()); pstmt.setString(3, jdbcDto.getName()); cnt = pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(null, pstmt, conn); } return cnt; } | cs |
|| Update
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | private int updateInfo(String mid, String mpwd) { int cnt = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("update jdbctest \n"); sql.append("set pwd = ? \n"); sql.append("where id = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, mpwd); pstmt.setString(2, mid); cnt = pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(null, pstmt, conn); } return cnt; } | cs |
|| Delete
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | private int deleteInfo(String did) { int cnt = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("delete from jdbctest \n"); sql.append("where id = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, did); cnt = pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(null, pstmt, conn); } return cnt; } | cs |
|| Select
> SelectOne
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | private JdbcDto selectById(String sid) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; JdbcDto jdbcDto = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("select * from jdbctest where id = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, sid); rs = pstmt.executeQuery(); if(rs.next()) { jdbcDto = new JdbcDto(); jdbcDto.setId(rs.getString("id")); jdbcDto.setPwd(rs.getString("pwd")); jdbcDto.setName(rs.getString("name")); jdbcDto.setJoinDate(rs.getString("joindate")); } } catch (Exception e) { e.printStackTrace(); } finally { close(rs, pstmt, conn); } return jdbcDto; } | cs |
> SelectAll
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | private List<JdbcDto> selectAll() { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<JdbcDto> list = new ArrayList<>(); try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("select * from jdbctest"); pstmt = conn.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); JdbcDto jdbcDto = null; while(rs.next()) { jdbcDto = new JdbcDto(); jdbcDto.setId(rs.getString("id")); jdbcDto.setPwd(rs.getString("pwd")); jdbcDto.setName(rs.getString("name")); jdbcDto.setJoinDate(rs.getString("joindate")); list.add(jdbcDto); } } catch (Exception e) { e.printStackTrace(); } finally { close(rs, pstmt, conn); } return list; } | cs |
|| JDBC Test 전체 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class JdbcTest { private final String driver = "com.mysql.cj.jdbc.Driver"; private final String url = "jdbc:mysql://127.0.0.1:0000/testdb?serverTimezone=UTC&useUniCode=yes&characterEncoding=UTF-8"; private final String dbid = "userId"; private final String dbpwd = "userPw"; public JdbcTest() { try { // 1. Driver Loading Class.forName(driver); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws IOException { JdbcTest test = new JdbcTest(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /* * 회원 등록 */ System.out.println("회원 등록 !!!"); JdbcDto jdbcDto = new JdbcDto(); System.out.print("아이디 : "); jdbcDto.setId(br.readLine()); System.out.print("비밀번호 : "); jdbcDto.setPwd(br.readLine()); System.out.print("이름 : "); jdbcDto.setName(br.readLine()); int cnt = test.insert(jdbcDto); if(cnt != 0) System.out.println("등록 성공!!!"); /* * 회원 검색 */ System.out.print("검색할 아이디 : "); String sid = br.readLine(); JdbcDto dto = test.selectById(sid); if(dto != null) { System.out.println(sid + "회원 정보!!!"); System.out.println("이름 : " + dto.getName()); System.out.println("비번 : " + dto.getPwd()); System.out.println("가입일 : " + dto.getJoinDate()); } else { System.out.println(sid + " 회원은 없습니다."); } /* * 회원 정보 수정 */ System.out.print("수정 할 회원 아이디 : "); String mid = br.readLine(); System.out.print("수정할 비밀 번호 : "); String mpwd = br.readLine(); cnt = test.updateInfo(mid, mpwd); System.out.println(cnt + "개 정보 수정!!!"); /* * 회원 탈퇴 */ System.out.print("탈퇴 할 회원 아이디 : "); String did = br.readLine(); cnt = test.deleteInfo(did); System.out.println(cnt + "명 탈퇴!!!"); /* * 전체 회원 정보 확인 */ System.out.println("--- 모든 회원 정보 ---"); System.out.println("이름\t아이디\t비밀번호\t가입일"); System.out.println("----------------------------------"); List<JdbcDto> list = test.selectAll(); for(JdbcDto _dto : list) { System.out.println(_dto); } } private List<JdbcDto> selectAll() { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<JdbcDto> list = new ArrayList<>(); try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("select * from jdbctest"); pstmt = conn.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); JdbcDto jdbcDto = null; while(rs.next()) { jdbcDto = new JdbcDto(); jdbcDto.setId(rs.getString("id")); jdbcDto.setPwd(rs.getString("pwd")); jdbcDto.setName(rs.getString("name")); jdbcDto.setJoinDate(rs.getString("joindate")); list.add(jdbcDto); } } catch (Exception e) { e.printStackTrace(); } finally { close(rs, pstmt, conn); } return list; } private int deleteInfo(String did) { int cnt = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("delete from jdbctest \n"); sql.append("where id = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, did); cnt = pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(null, pstmt, conn); } return cnt; } private int updateInfo(String mid, String mpwd) { int cnt = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("update jdbctest \n"); sql.append("set pwd = ? \n"); sql.append("where id = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, mpwd); pstmt.setString(2, mid); cnt = pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(null, pstmt, conn); } return cnt; } private JdbcDto selectById(String sid) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; JdbcDto jdbcDto = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("select * from jdbctest where id = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, sid); rs = pstmt.executeQuery(); if(rs.next()) { jdbcDto = new JdbcDto(); jdbcDto.setId(rs.getString("id")); jdbcDto.setPwd(rs.getString("pwd")); jdbcDto.setName(rs.getString("name")); jdbcDto.setJoinDate(rs.getString("joindate")); } } catch (Exception e) { e.printStackTrace(); } finally { close(rs, pstmt, conn); } return jdbcDto; } private int insert(JdbcDto jdbcDto) { int cnt = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection(url, dbid, dbpwd); StringBuilder sql = new StringBuilder(); sql.append("insert into jdbctest (id, pwd, name, joindate) \n"); sql.append("values (?, ?, ?, now())"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, jdbcDto.getId()); pstmt.setString(2, jdbcDto.getPwd()); pstmt.setString(3, jdbcDto.getName()); cnt = pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(null, pstmt, conn); } return cnt; } private void close(ResultSet rs, PreparedStatement pstmt, Connection conn) { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } | cs |
'Web' 카테고리의 다른 글
[Lexical scoping & Closure] 어휘적 범위 지정, 클로저 (0) | 2021.01.15 |
---|---|
[Vue.js] Vue 기본 내용 정리 (0) | 2020.11.21 |
[Node.js] cheerio module 로 크롤링하기 (0) | 2020.06.23 |
[Node.js] Express Framework 사용하기 (0) | 2020.06.22 |
[Node.js] mySQL 연동 (0) | 2020.06.22 |