본문 바로가기
JAVA

mySQL : data insert method (mysql 데이터 삽입 메소드)

by 낫싱 2020. 3. 12.
728x90
반응형

public static void dataInsert(ArrayList<String> lines){ //결과값을 반환할게 없으니 void 유지

String[] words=null;

words=lines.get(0).split(", "); // student.txt <= ", "로 나뉘어있음. //이거 반복●

// 0 1 2 3 4 5

// 1292001, 900424-1825409, 김광식, 3, 서울, 920

String name = ChangeEncoding.toLatin(words[2]); //이거 반복●

int y=Integer.parseInt(words[3]); //이거 반복●

String addr=ChangeEncoding.toLatin(words[4]); //이거 반복●

// String queryInsert="insert into stu_table values ('"+words[0]+"','"+words[1]+"','"+name+"', "+y+", '"+addr+"','"+words[5]+"')"; //이거 반복●

//System.out.println(queryInsert); // 실제로 값이 제대로 출력되는지 확인

String newQueryInsert="insert into stu_table values (?, ?, ?, ?, ?, ?)"; //?로 표현할 수 있는 부분은 데이터가 들어가는 부분만 가능('?'처리 가능)

try {

Statement stmt =conn.createStatement();

PreparedStatement pstmt=conn.prepareStatement(newQueryInsert);

pstmt.setString(1, words[0]); //테이블 필드 인덱스 번호는 반드시 1로 시작한다.(물음표의 첫번쨰 위치도 1로 시작)

pstmt.setString(2, words[1]); //데이터가 변수로 되어있으면 prepare 사용, 일반 문자로 되어있으면 statement 사용

pstmt.setString(3, name);

pstmt.setInt(4, y);

pstmt.setString(5, addr);

pstmt.setString(6, words[5]);

int n=pstmt.executeUpdate();

if(n>0){

System.out.println("Pstmt 생성 DATA INSERT 성공");

}

/* ■■■■■■■■■■■■■■ 데이터를 ?표처리하지 않고 변수를 직접 넣어서 Query문 실행하는 방법

for(int i=0;i<lines.size();i++){

words=lines.get(i).split(", ");

String name = ChangeEncoding.toLatin(words[2]);

int y=Integer.parseInt(words[3]);

String addr=ChangeEncoding.toLatin(words[4]);

insert문을 작은 따옴표 없이 수정

쿼리내부에 데이터부분 변수를 사용할 경우(특히 문자열 부분), 쿼리문의 데이터부분을 ?로 처리한 후, 나중에 메서드를 통하여 ?위치에 데이터를 설정 할 수 있다.

String queryInsert="insert into stu_table values ('"+words[0]+"','"+words[1]+"','"+name+"', "+y+", '"+addr+"','"+words[5]+"')";

int n=stmt.executeUpdate(queryInsert);

if(n>0){

System.out.println("data insert success"); //★★★추후 for문으로 전체 데이터를 입력한다.

}

}*/

// int n=stmt.executeUpdate(queryInsert); //이거 반복●

// if(n>0){ //이거 반복●

// System.out.println("data insert success"); //★★★추후 for문으로 전체 데이터를 입력한다. //이거 반복●

// } //이거 반복●

} catch (SQLException e) {

System.out.println("conn.createStatement 오류 "+e.getMessage());

}

}//public static void dataInsert END

728x90
반응형

'JAVA' 카테고리의 다른 글

20200511 - 스프링(스프링부트 - STS)  (0) 2020.05.11
파일 읽어들이기 메소드(FileReaderMethod)  (0) 2020.03.12

댓글