package com.c2j.jdbc.preparedstatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCUpdateTableUsingPreparedStatement {
public static void main(String[] args) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
int rows=0;
String sql = "UPDATE EMPLOYEE SET LAST=? WHERE ID=?";
try {
con = getOracleDBConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "SUMANTH");
pstmt.setInt(2, 1);
rows=pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
}
System.out.println("Number of Rows updated in EMPLOYEE table = "+rows);
}
private static Connection getOracleDBConnection(){
//Here TEST is oracle database name.
String ORACLE_DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:TEST";
String ORACLE_DB_USER = "system";
String ORACLE_DB_PASSWORD = "system";
/* From JDBC 4.0(from Java6) onwards we no need to load data base driver
* using class.forName(); Just add the database driver
* jar(ojdbc6.jar for oracle) in the class path.
* It will load when Drivermanager.getConnection method called.
*/
Connection oracleDbConnection = null;
try {
oracleDbConnection = DriverManager.getConnection
(ORACLE_DB_CONNECTION, ORACLE_DB_USER,ORACLE_DB_PASSWORD);
return oracleDbConnection;
} catch (SQLException e) {
e.printStackTrace();
}
return oracleDbConnection;
}
}