JDBC_executeUpdate1.htm
  • example executeUpdate:: using Statement
  • Single Update (Transaction)
  • Steps:
    • Create a statement object
    • Autocommit off
    • executeUpdate();
    • Autocommit or commit or rollback
Update Code :

Code :

package javatemplate1;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
*
* @author Manas14
*/
public class JavaTemplate1 {
// private static String dbURL;

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("main block executing ");
Connection c = null; Statement st = null;
// ResultSet rs = null; // result set object
//String dbURL = "jdbc:mysql://localhost/test?";
String dbURL = "jdbc:postgresql://localhost:5432/pgsdemo1";
String user = "postgres"; String pwd = "postgre_manas9";
//String user = "manas237"; String password = "pwmanas237";
// Properties param = new Properties();
// connecting to db
try {
//replacing Class.forName("org.postgresql.Driver");
// param.put("user",user); param.put("password",pwd);
c = DriverManager.getConnection(dbURL,user,pwd);
System.out.println("Connected to database successfully");
c.setAutoCommit(false);
st = c.createStatement();
//deptno 20 eno 7369 name SMITH JOB CLERK
//manager 7902 hired1980-12-17 sal 800.0
String sql = "UPDATE emp SET sal = 890.00 WHERE EMPNO = 7369";
st.executeUpdate(sql);
c.setAutoCommit(true);
ResultSet rs = st.executeQuery("SELECT * FROM emp;");
//PreparedStatement updateSal = con.prepareStatement(
// "UPDATE emp SET SAL= 900 WHERE EMPNP = 7369 AND DEPTNO = 20");
// rs = st.execute();
while(rs.next())
{
//int dept = rs.getInt("EMPNO");
int eno= rs.getInt("EMPNO");
String name = rs.getString("ename");
String job = rs.getString("JOB");
int manager = rs.getInt("MGR");
Date date = rs.getDate("HIREDATE");
float salary = rs.getFloat("SAL");
// double commision = rs.getInt("COMM");
int deptno = rs.getInt("DEPTNO");

System.out.println("deptno " + deptno + " eno " + eno+ " name "+
name + " JOB " + job +" manager " + manager +
" hired" + date + " sal " + salary );
}

} catch (SQLException ex) { ex.getErrorCode();
String message = ex.getMessage();
System.out.println(message);
} finally {
System.out.println("going through final block");
try {
if (st== null || st.isClosed()) {
} else {
st.close();
}
if (c != null && !c.isClosed()) {
c.close(); }
} catch (SQLException ex) { ex.getErrorCode();
ex.getMessage();
}
}
System.out.println("dis-Connected to database successfully");
// st.close(); con.commit();con.close();
}

}

Runtime View

Using PHP