본문 바로가기

Database/MySQL

[MySQL] Eclipse DB연동(InsertTest, UpdateTest)

[InsertTest]

 

사원번호, 이름, 급여, 입사일 레코드를 추가하라.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertTest {
	
	Connection con = null;
	PreparedStatement pstmt = null;

	public InsertTest() {
		
	}
	
	public void empInsert() {
		// 사원번호, 이름, 급여, 입사일 레코드 추가
		
		
		try {
			// 1. 드라이브 로딩
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			// 2. DB 연결
			con = DriverManager.getConnection("jdbc:mysql://localhost/demo", "root", "0000");
			
			//3. PreparedStatement 객체 생성 - 쿼리문을 이용(문자열)
			// 사원번호 : 5555, 이름 : Kim, 급여 : 4500, 입사일 : 현재 날짜,시간
			//String sql = "insert into emp(empno, ename,sal, hiredate) values(5555, 'Kim', 4500, now())";
			
            
            // 여러명 입력하는 경우 ?로 대체										  1  2  3
			String sql2 = "insert into emp(empno, ename,sal, hiredate) values(?, ?, ?, now())";
			pstmt = con.prepareStatement(sql2);
			
			// ?에 값 셋팅
			pstmt.setInt(1, 5555);
			pstmt.setString(2, "Kim");
			pstmt.setDouble(3, 4500);
			
			// 4. 실행
			// 쿼리문을 실행하여 추가된 레코드 수 반환 cnt=0이면 레코드 추가 실패
			int cnt = pstmt.executeUpdate();
			if (cnt>0) {
				System.out.println("레코드가 추가되었습니다.");
			} else {
				System.out.println("레코드 추가 실패하였습니다.");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(pstmt != null) pstmt.close();
				if(con != null) pstmt.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		
		new InsertTest().empInsert();
		
	}
}

 

 

excuteQurery()는 ResultSet 반환

ResultSet : 쿼리의 결과를 가져오는 클래스
안에 있는 메소드(next())로 표 첫번째에 있는 행 데이터를 가져오려면 포인트를 옮겨줘야한다. 
ResultSet 객체에는 표 형식으로 데이터가 담겨있다.

excuteUpdate()는 int형 반환

몇개의 레코드가 수정되었는지 반환됨
Insert, Update, Delete 쿼리를 실행한다.

 

 

[에러]

com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:123)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1350)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at InsertTest.empInsert(InsertTest.java:40)
at InsertTest.main(InsertTest.java:62)

 

 

Workbench에서 commit을 하지 않은 상태(savepoint, rollback 연습한 후 commit을 안 해줌)인데

다른 프로그램에서 db 작업을 하려고 하니 에러가 떴다.

 

↓ Workbench에서 commit;을 실행한 후 다시 run하면 성공적으로 레코드가 추가된다.

Kim 사원 추가됨

 

 


 

[UpdateTest]

 

사원번호와 급여를 입력받아 해당 사원의 급여를 수정하라.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class UpdateTest {
	Scanner scn = new Scanner(System.in);
	Connection con = null;
	PreparedStatement pstmt = null;
	
	public UpdateTest() {
		// TODO Auto-generated constructor stub
	}
	
	public void start() {
		// 사원번호와 급여를 입력받아 해당 사원의 급여를 수정하라.
		
		// 데이터 입력
		System.out.println("수정할 사원번호 : ");
		int empno = scn.nextInt();
		
		System.out.println("수정할 급여 : ");
		int sal = scn.nextInt();
		
		try {
			
			// 1. 드라이브 생성
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			// 2. DB 연결
			con = DriverManager.getConnection("jdbc:mysql://localhost/demo","root","0000");
			
			// 3. PreparedStatement 객체 생성
			String sql = "update emp set sal=? where empno=?";
			pstmt = con.prepareStatement(sql);
			
			// 3-1. 데이터 값 셋팅
			pstmt.setInt(1,sal);
			pstmt.setInt(2, empno);
			
			// 4. 실행(수정한 레코드 수 리턴)
			int result = pstmt.executeUpdate();
			if (result>0) {
				System.out.println(result+"개의 레코드가 수정되었습니다.");
			} else {
				System.out.println("레코드 수정 실패하였습니다.");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//5. db 닫기
			try {
				if(con!=null) pstmt.close();
				if(pstmt!=null) pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new UpdateTest().start();
	}

}

급여가 4500에서 5000으로 변경됨

 

 


 

[DeleteTest]

 

사원번호를 입력받아 입력 받은 사원을 삭제하라.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class DeleteTest {

	Scanner scn = new Scanner(System.in);
	Connection con = null;
	PreparedStatement pstmt = null;
	
	public DeleteTest() {

	}

	public void start() {
		
		try {
			
			// 사원번호를 입력받아 입력 받은 사원을 삭제하라.
			System.out.println("삭제할 사원번호 : ");
			// nextLine으로도 응용해보기
			int empno = Integer.parseInt(scn.nextLine());
			
			// 1. 드라이브 생성
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			//2. db 연결
			con = DriverManager.getConnection("jdbc:mysql://localhost/demo","root","0000");
			
			// 3. 객체 생성
			String sql = "delete from emp where empno=?";
			pstmt = con.prepareStatement(sql);
			// 3-1. 데이터 값 셋팅
			pstmt.setInt(1,empno);
			
			// 4. 실행
			int result = pstmt.executeUpdate();
			if(result>0) {
				System.out.println(result+"개의 레코드가 삭제되었습니다.");
			}else {
				System.out.println("레코드 삭제 실패하였습니다.");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
			//5. db 종료
			try {
				if(con!=null) pstmt.close();
				if(pstmt!=null) pstmt.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
			
		}
	}
	public static void main(String[] args) {
		new DeleteTest().start();

	}

}