-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEx06_UserSelect.java
61 lines (54 loc) · 1.69 KB
/
Ex06_UserSelect.java
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
package jdbc.day01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Ex06_UserSelect {
public static void main(String[] args) {
Connection conn = null;
try {
//JDBC Driver 등록
Class.forName("com.mysql.cj.jdbc.Driver");
//연결하기
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/thisisjava",
"nostal",
"dbsdud94"
);
//매개변수화된 SQL 문 생성
String sql = "" +
"SELECT userid, username, userpassword, userage, useremail " +
"FROM users " +
"WHERE userid=?";
//PreparedStatement 얻기 및 값 지정
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "winter");
//SQL 문 실행 후, ResultSet을 통해 데이터 읽기
ResultSet rs = pstmt.executeQuery();
if(rs.next()) { //1개의 데이터 행을 가져왔을 경우
Ex06_User user = new Ex06_User();
user.setUserId(rs.getString("userid"));
user.setUserName(rs.getString("username"));
user.setUserPassword(rs.getString("userpassword"));
user.setUserAge(rs.getInt(4)); //컬럼 순번을 이용
user.setUserEmail(rs.getString(5)); //컬럼 순번을 이용
System.out.println(user);
} else { //데이터 행을 가져오지 않았을 경우
System.out.println("사용자의 아이디가 존재하지 않음");
}
rs.close();
//PreparedStatement 닫기
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn != null) {
try {
//연결 끊기
conn.close();
} catch (SQLException e) {}
}
}
}
}