* 순서
1. Driver Loading
2. Connection
3. 쿼리 문장 작성
4. 자원 반납
1. Driver Loading
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
2. Connection
Connection con;
try {
String url = "jdbc:mysql://127.0.0.1:3306/[데이터베이스 이름 넣기]?erverTimezone=UTC&useUniCode=yes&characterEncoding=UTF-8";
String id = "[id 넣기]";
String pwd = "[pwd 넣기]";
con = DriverManager.getConnection(url, id, pwd);
} catch (SQLException e) {
e.printStackTrace();
}
3. 쿼리 문장 작성, 4. 자원반납
JdbcTest jt = new JdbcTest();
Statement st = null;
ResultSet rs = null;
try {
st = jt.con.createStatement();
String sql = "select employee_id, first_name, last_name, salary from employees";
rs = st.executeQuery(sql);
while (rs.next()) {
String eid = rs.getString("employee_id");
String fname = rs.getString("first_name");
String lname = rs.getString("last_name");
int salary = rs.getInt("salary");
System.out.println(eid + " " + fname + " " + lname);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
st.close();
jt.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}