๐ RoleDao.java๋ MySQL๊ณผ Role.java ํด๋์ค๋ฅผ ์ด์ฉํ์ฌ ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๋ ํด๋์ค ์ด๋ค.
JDBC API ์ฌ์ฉ์ ์ํด Class.forName
๋ฉ์๋๋ฅผ ์ด์ฉํ์ฌ JDBC ๋๋ผ์ด๋ฒ ๋ก๋ฉ
DB ๋ง๋ค ํด๋์ค ์ด๋ฆ์ด ๋ค๋ฅด๋ฏ๋ก ํด๋น DB ์ด๋ฆ์ ์ ํํ๊ฒ ๋ฃ์ด์ผ ํ๋ค.
๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฐ๊ฒฐ ์ค์
//๋๋ผ์ด๋ฒ ๋ก๋ฉ
Class.forName("com.mysql.jdbc.Driver");
//์ปค๋ฅ์
๊ฐ์ฒด
conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
//insert ๋ ๊ฒฐ๊ณผ ๊ฑด์๋ฅผ ๋ํ๋ผ int ํ ๋ณ์ ์ ์ธ
int insertCount = 0;
Connection conn = null;
PreparedStatement ps = null;
String sql = "insert into role(role_id, description) values (?, ?)";
ps = conn.prepareStatement(sql);
ps.setInt(1, role.getRoleId());
ps.setString(2, role.getDescription())
insertCount = ps.executeUpdate(); //๋ช
๋ ์ด ์คํ
๐ role_id ์ 500, description ์ "CTO" ์ธ ๋ฐ์ดํฐ๋ฅผ ์ฝ์ ํด๋ณด์.
package kr.or.connect.jdbcexam;
import kr.or.connect.jdbcexam.dao.RoleDao;
import kr.or.connect.jdbcexam.dto.Role;
public class JDBCexam2 {
//Insert
public static void main(String[] args) {
int roleId = 500;
String description = "CTO";
Role role = new Role(roleId, description);
RoleDao dao = new RoleDao();
int insertCount = dao.addRole(role);
System.out.println(insertCount);
}
}
๋ง์ง๋ง ํ์ ์ ์์ ์ผ๋ก ๋ฐ์ดํฐ๊ฐ ์ฝ์
๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
๐ ์ ์ฒด ์ฝ๋
RoleDao.java - addRole()
package kr.or.connect.jdbcexam.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import kr.or.connect.jdbcexam.dto.Role;
public class RoleDao {
private static String dburl = "jdbc:mysql://localhost:3306/connectdb1?serverTimezone=Asia/Seoul&useSSL=false";
private static String dbUser = "connectuser";
private static String dbpasswd = "";
//Insert
public int addRole(Role role) {
int insertCount = 0;
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
String sql = "insert into role(role_id, description) values (?, ?)";
ps = conn.prepareStatement(sql);
ps.setInt(1, role.getRoleId());
ps.setString(2, role.getDescription());
insertCount = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
return insertCount;
}
JDBCexam2.java
package kr.or.connect.jdbcexam;
import kr.or.connect.jdbcexam.dao.RoleDao;
import kr.or.connect.jdbcexam.dto.Role;
public class JDBCexam1 {
public static void main(String[] args) {
RoleDao dao = new RoleDao();
Role role = dao.getRole(100);
System.out.println(role);
}
}