on
Java JDBC PrepareStatement
Java JDBC PrepareStatement
//Insert
public class Statement_insert2 {
public static void main( String [] args) {
String driver = "oracle.jdbc.driver.OracleDriver" ; // 드라이버 정보
String url = "jdbc:oracle:thin:@localhost:1521:xe" ; // 접속db정보 : 주소/포트번호/sid
String userid = "scott" ; // 접속계정
String passwd = "tiger" ;
Connection con = null ;
PreparedStatement pstmt = null ;
ResultSet rs = null ;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
String sql = "insert into dept(deptno, dname, loc)"
+ "values (?, ?, ? )" ;
// ?의 개수에 따라서 index가 지정, 여기서는 ? 세개니까 3개 인덱스가 지정됨
pstmt = con.prepareStatement(sql);
pstmt.setInt( 1 , 13 ); //? 자리에 맞춰서
pstmt.setString( 2 , "개발" );
pstmt.setString( 3 , "서울" );
int num = pstmt.executeUpdate(); //1번째업데이트 실행
String sql2 = "insert into dpet(deptno, dname, loc)"
+ "values (?, ?, ?)" ; //2번째 업데이트
pstmt.setInt( 1 , 14 );
pstmt.setString( 2 , "연구2" );
pstmt.setString( 3 , "경기" );
int num2 = pstmt.executeUpdate(); //2번째 업데이트 실행
System . out . println ( "실행된 레코드 개수 : " + (num + num2));
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//Delete 위아래 부분은 동일
try {
con = DriverManager.getConnection(url, userid, passwd);
String sql = "delete from dept where deptno = ? or deptno = ?" ;
pstmt = con.prepareStatement(sql);
pstmt.setInt( 1 , 13 );
pstmt.setInt( 2 , 14 );
int num = pstmt.executeUpdate();
System . out . println ( "삭제 : " + num);
//Update 위아래 부분은 동일
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
String sql = "update dept set dname = ?, loc = ?"
+ "where deptno = ?" ;
pstmt = con.prepareStatement(sql);
pstmt.setString( 1 , "aa" );
pstmt.setString( 2 , "bb" );
pstmt.setInt( 3 , 98 );
int num = pstmt.executeUpdate();
from http://cocoshin.tistory.com/27 by ccl(A) rewrite - 2021-11-26 02:28:21