728x90
package database;
import java.sql.*;
public class DBconnection {
private Connection con;
private Statement st;
private ResultSet rs;
public DBconnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/study", "root", "???");
st = con.createStatement();
}
catch(Exception e) {
System.out.println("데이터베이스 연결 오류 : " + e.getMessage());
}
}
public int insert(int ID, String Name, String BirthDay, String Major) throws SQLException {
String sql = "insert into students values(?, ?, ?, ?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1,ID);
pst.setString(2,Name);
pst.setString(3,BirthDay);
pst.setString(4,Major);
int result = pst.executeUpdate(); // 실패하면 0을반환, 성공하면 insert된 행의 개수가 반환
con.close(); // 연결끊어줌
st.close();
return result;
}
public int update(int ID, String Name, String BirthDay, String Major) throws SQLException {
String sql = "update students set Name = ?, BirthDay = ?, Major =? where id = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,Name);
pst.setString(2,BirthDay);
pst.setString(3,Major);
pst.setInt(4,ID);
int result = pst.executeUpdate(); // 실패하면 0을반환, 성공하면 update된 행의 개수가 반환
con.close(); // 연결끊어줌
st.close();
return result;
}
public int delete(int ID) throws SQLException {
String sql = "delete from students where id = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1,ID);
int result = pst.executeUpdate();
con.close();
st.close();
return result;
}
}
여기는 사실 아직 스스로 완벽하게 이해한 부분이 거의 없다. 그냥 하라는 데로 함. 그래서 다시 공부해야 된다.
728x90
'언어 > java' 카테고리의 다른 글
[이클립스] Eclipse 빨간줄, 노란줄, 초록줄 형광펜 없애기 (0) | 2023.09.19 |
---|---|
[java] 학생 관리 프로그램 (4) - db 연결 후 select (0) | 2022.04.24 |
[java] 학생 관리 프로그램 (2) (0) | 2022.04.24 |
[java] 학생 관리 프로그램 (1) (0) | 2022.04.24 |
[java] 중복 없는 숫자 랜덤 생성기 (0) | 2022.04.24 |