// Import the following packages to use JDBC.
import java.sql.*;
import java.io.*;
import oracle.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class MakeChanges {
public static void main( String args[ ] ) throws SQLException {
String user = "C##user.id";
String password = "password";
String database = "65.52.222.73:1521/cdb1";
// Open an OracleDataSource and get a connection.
OracleDataSource ods = new OracleDataSource( );
ods.setURL ( "jdbc:oracle:thin:@" + database );
ods.setUser ( user );
ods.setPassword( password );
Connection conn = ods.getConnection( );
try {
Statement stmt = conn.createStatement( );
// Clear the table EMP_TBL.
stmt.executeUpdate( "DELETE FROM emp_tbl2" );
// Prepare to insert two employees in the emp_tbl2 table and
// use the create sequence for the empno of the employees.
String cmd = "INSERT INTO emp_tbl2 ";
cmd += "SELECT empid_seq2.NEXTVAL, ? FROM DUAL";
PreparedStatement pstmt = conn.prepareStatement( cmd );
// Add the first employee and the first ? is for ename.
pstmt.setString( 1, args[0].trim( ) );
// Do the insertion.
pstmt.execute( );
// Add the second employee and the first ? is for ename.
pstmt.setString( 1, args[1].trim( ) );
pstmt.execute ( );
// Add the third employee with an employee number 507.
// Prepare to insert new names in the EMP_TBL table.
cmd = "INSERT INTO emp_tbl2( empno, ename ) VALUES( ?, ? )";
pstmt = conn.prepareStatement( cmd );
pstmt.setInt ( 1, 507 ); // The first ? is for empno
pstmt.setString( 2, args[2].trim( ) ); // The second ? is for ename
pstmt.execute ( );
// Close the Statement.
pstmt.close( );
cmd = "SELECT * FROM emp_tbl2 ORDER By empno";
ResultSet rset = stmt.executeQuery( cmd );
while ( rset.next( ) ) {
System.out.print( "empno: " + rset.getInt( 1 ) );
System.out.print( "ename: " + rset.getString( 2 ) );
}
// Close the ResultSet and Statement.
rset.close ( );
stmt.close( );
}
catch( SQLException e ) { System.out.println( e ); }
conn.close( );
}
}
|