| 
  
   Size: 879 
  
  Comment:  
 | 
  
   Size: 11452 
  
  Comment:  
 | 
| Deletions are marked like this. | Additions are marked like this. | 
| Line 5: | Line 5: | 
| JDBC driver for JDK 1.6 (ojdbc6.jar): http://download.oracle.com/otn/utilities_drivers/jdbc/11204/ojdbc6.jar == Maven local repository install == mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true {{{#!highlight xml <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency> }}}  | 
|
| Line 13: | Line 26: | 
| SELECT * FROM ALL_TAB_COLUMNS WHERE TABLE_NAME='AAA'; | |
| Line 35: | Line 49: | 
== Partinioning == http://www.orafaq.com/wiki/Interval_partitioning http://docs.oracle.com/cd/E11882_01/server.112/e25523/part_admin005.htm http://docs.oracle.com/cd/E11882_01/server.112/e25523/part_admin002.htm {{{#!highlight sql select table_name,partition_name,num_rows from user_tab_partitions where table_name='TEST'; }}} Other views: * DBA_TAB_PARTITIONS * ALL_TAB_PARTITIONS * USER_TAB_PARTITIONS == Sequence creation == {{{#!highlight sql CREATE SEQUENCE sample_seq START WITH 1 INCREMENT BY 1; CREATE SEQUENCE sample_seq2 MINVALUE 1 START WITH 1 INCREMENT BY 1; SELECT * FROM ALL_SEQUENCES; -- show all sequences }}} == Sequence usage sample == {{{#!highlight sql -- table creation CREATE TABLE Employee ( idEmployee number(12), name varchar2(255), lastName varchar2(255), constraint pkIdEmployee PRIMARY KEY(idEmployee) ); -- sequence creation CREATE SEQUENCE seqEmplyee start with 1 increment by 1 minvalue 1 maxvalue 65536; -- insert values INSERT INTO Employee (idEmployee,name,lastName) values(seqEmplyee.nextval,'Bart','Simpson'); INSERT INTO Employee (idEmployee,name,lastName) values(seqEmplyee.nextval,'Peter','Griffin'); INSERT INTO Employee (idEmployee,name,lastName) values(seqEmplyee.nextval,'Homer','Simpson'); -- check sequence current value SELECT seqEmplyee.currval FROM dual; }}} == User and table space creation in Oracle XE == {{{#!highlight sql -- login with system user create tablespace christs datafile 'c:\christs.dbf' size 100m; create user chris identified by 12345678 default tablespace christs; alter user chris quota unlimited on christs; grant create session to chris; grant create table to chris; -- login with user chris create table CHRIS.test ( name varchar(255) ) tablespace chris; insert into CHRIS.test (name) values('Test name 1234'); -- login with system user -- user alice to just run selects create user alice identified by 12345678 default tablespace christs; grant create session to alice; grant select on CHRIS.test to alice; -- login with alice select * from CHRIS.test; }}} == Oracle Database 11g Express Edition == Download from [[ http://www.oracle.com/technetwork/database/database-technologies/express-edition/overview/index.html | Oracle site ]] * Run setup.exe * Next * Accept * Next * c:\oraclexe * Port TNS 1521 * Port MTS 2030 * Port Http 8081 * Next * For user sys and system password ******** * Next * Install * Finish === Info === * Default SID xe . * Default JDBC driver JAR ojdbc6.jar . * JDBC Url jdbc:oracle:thin:@//localhost:1521/XE == Returning a JDBC result set from an Oracle stored procedure == http://enterprisedt.com/publications/oracle/result_set.html Create function: {{{#!highlight sql CREATE OR REPLACE FUNCTION sp_get_stocks(v_price IN NUMBER) RETURN sys _refcursor AS stock_cursor sys_refcursor; BEGIN OPEN stock_cursor FOR SELECT ric,price,updated FROM stock_prices WHERE price < v_price; RETURN stock_cursor; END; }}} Test function: {{{#!highlight sql var results refcursor exec :results := sp_get_stocks(20.0) print results }}} JDBC invocation {{{#!highlight java //String query = "begin ? := sp_get_stocks(?); end;"; //JDBC syntax String query = "{ call ? := sp_get_stocks(?) }"; CallableStatement stmt = conn.prepareCall(query); // register the type of the out param - an Oracle specific type stmt.registerOutParameter(1, OracleTypes.CURSOR); // set the in param stmt.setFloat(2, price); // execute and retrieve the result set stmt.execute(); ResultSet rs = (ResultSet)stmt.getObject(1); // print the results while (rs.next()) { System.out.println(rs.getString(1) + "\t" + rs.getFloat(2) + "\t" + rs.getDate(3).toString()); } }}} http://docs.oracle.com/cd/E18283_01/appdev.112/e13995/oracle/jdbc/OracleCallableStatement.html {{{#!highlight java // SQL92 syntax CallableStatement cs1 = conn.prepareCall ( "{call proc (?,?)}" ) ; // stored proc CallableStatement cs2 = conn.prepareCall ( "{? = call func (?,?)}" ) ; // stored func // Oracle PL/SQL block syntax CallableStatement cs3 = conn.prepareCall ( "begin proc (?,?); end;" ) ; // stored proc CallableStatement cs4 = conn.prepareCall ( "begin ? := func(?,?); end;" ) ; // stored func }}} http://www.informit.com/articles/article.aspx?p=26251&seqNum=6 {{{#!highlight sql CREATE OR REPLACE PROCEDURE p_highest_paid_emp (ip_deptno NUMBER, op_empno OUT NUMBER, op_ename OUT VARCHAR2, op_sal OUT NUMBER) IS v_empno NUMBER; v_ename VARCHAR2(20); v_sal NUMBER; BEGIN SELECT empno, ename, sal INTO v_empno, v_ename, v_sal FROM emp e1 WHERE sal = (SELECT MAX(e2.sal) FROM emp e2 WHERE e2.deptno = e1.deptno AND e2.deptno = ip_deptno) AND deptno = ip_deptno; op_empno := v_empno; op_ename := v_ename; op_sal := v_sal; END; / }}} {{{#!highlight java import java.sql.*; public class StProcExample { public static void main(String[] args) throws SQLException { int ret_code; Connection conn = null; try { //Load and register Oracle driver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); //Establish a connection conn = DriverManager.getConnection("jdbc:oracle:thin:@training:1521: Oracle", "oratest", "oratest"); int i_deptno = 10; CallableStatement pstmt = conn.prepareCall("{call p_highest_ paid_emp(?,?,?,?)}"); pstmt.setInt(1, i_deptno); pstmt.registerOutParameter(2, Types.INTEGER); pstmt.registerOutParameter(3, Types.VARCHAR); pstmt.registerOutParameter(4, Types.FLOAT); pstmt.executeUpdate(); int o_empno = pstmt.getInt(2); String o_ename = pstmt.getString(3); float o_sal = pstmt.getFloat(4); System.out.print("The highest paid employee in dept " +i_deptno+" is: "+o_empno+" "+o_ename+" "+o_sal); pstmt.close(); conn.close(); } catch (SQLException e) {ret_code = e.getErrorCode(); System.err.println(ret_code + e.getMessage()); conn.close();} } } }}} http://oracle-base.com/articles/misc/using-ref-cursors-to-return-recordsets.php {{{#!highlight sql CREATE OR REPLACE PROCEDURE get_emp_rs (p_deptno IN emp.deptno%TYPE, p_recordset OUT SYS_REFCURSOR) AS BEGIN OPEN p_recordset FOR SELECT ename, empno, deptno FROM emp WHERE deptno = p_deptno ORDER BY ename; END GetEmpRS; / }}} {{{#!highlight java import java.sql.*; import oracle.jdbc.*; public class TestResultSet { public TestResultSet() { try { DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection("jdbc:oracle:oci:@w2k1", "scott", "tiger"); CallableStatement stmt = conn.prepareCall("BEGIN get_emp_rs(?, ?); END;"); stmt.setInt(1, 30); // DEPTNO stmt.registerOutParameter(2, OracleTypes.CURSOR); //REF CURSOR stmt.execute(); ResultSet rs = ((OracleCallableStatement)stmt).getCursor(2); while (rs.next()) { System.out.println(rs.getString("ename") + ":" + rs.getString("empno") + ":" + rs.getString("deptno")); } rs.close(); rs = null; stmt.close(); stmt = null; conn.close(); conn = null; } catch (SQLException e) { System.out.println(e.getLocalizedMessage()); } } public static void main (String[] args) { new TestResultSet(); } } }}} == Exceptions == {{{#!highlight sql -- BEGIN EXCEPTION WHEN others THEN dbms_output.put_line('Ups ....!'); END; }}} == Convert to date == {{{ TO_DATE('2013/07/19', 'yyyy/mm/dd') Result: date value of July 19, 2013 TO_DATE('071913', 'MMDDYY') Result: date value of July 19, 2013 TO_DATE('20120311', 'yyyymmdd') Result: date value of Mar 11, 2012 }}} == Number updated rows == * SQL%ROWCOUNT * numberRows := SQL%ROWCOUNT; == Return first non null expression == * use NVL function , Oracle specific * use COALESCE function , ANSI 92 {{{#!highlight sql UPDATE xyz set fieldx = COALESCE(fieldx_param, fieldx) where idx=idx_p; }}} == Get unique identifier GUID == https://docs.oracle.com/cd/B12037_01/server.101/b10759/functions153.htm SYS_GUID generates and returns a globally unique identifier (RAW value) made up of 16 bytes. On most platforms, the generated identifier consists of a host identifier, a process or thread identifier of the process or thread invoking the function, and a nonrepeating value (sequence of bytes) for that process or thread. {{{#!highlight sql select sys_guid() from dual; }}} == Data types == * number * nvarchar2 * int * real == Limit number of rows (rownum) == {{{#!highlight sql select * from tablex where rownum <=10; }}} == Docker container Oracle DB XE 21c == Should have [[https://www.oracle.com/database/technologies/oracle21c-linux-downloads.html|oracle-database-xe-21c-1.0-1.ol8.x86_64.rpm]] in the same folder of the Dockerfile and steps.sh file. === Dockerfile === {{{#!highlight sh FROM oraclelinux:8.7 ENV ORACLE_DOCKER_INSTALL=true CMD ["/bin/bash"] }}} === steps.sh === {{{#!highlight sh #!/bin/sh yum update -y yum install -y oracle-database-preinstall-21c yum -y localinstall /mnt/oracle-database-xe-21c-1.0-1.ol8.x86_64.rpm echo -e "TestOracle01\nTestOracle01\n" | /etc/init.d/oracle-xe-21c configure echo "PATH=/opt/oracle/product/21c/dbhomeXE/bin/:$PATH" >> ~/.bashrc echo "export ORACLE_HOME=/opt/oracle/product/21c/dbhomeXE/" >> ~/.bashrc }}} === Steps === {{{#!highlight sh docker build -t oracledb_test . docker run --rm -dit --name oraclelinux -p 1521:1521 -v $PWD:/mnt/ -e ORACLE_DOCKER_INSTALL=true oracledb_test docker exec -it oraclelinux bash cd /mnt/ time sh steps.sh # real 24m43.345s source ~/.bashrc sqlplus system/TestOracle01@localhost/xe SELECT table_name FROM dba_tables; exit }}}  | 
Oracle
http://docs.oracle.com/cd/B19306_01/index.htm
JDBC driver for JDK 1.6 (ojdbc6.jar): http://download.oracle.com/otn/utilities_drivers/jdbc/11204/ojdbc6.jar
Maven local repository install
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true
Get schemas in DB
   1 SELECT DISTINCT USERNAME FROM DBA_USERS;
Get columns from table
Get indexes from table
http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_1069.htm
Get code from stored procedure
Show schema and table
Partinioning
http://www.orafaq.com/wiki/Interval_partitioning
http://docs.oracle.com/cd/E11882_01/server.112/e25523/part_admin005.htm
http://docs.oracle.com/cd/E11882_01/server.112/e25523/part_admin002.htm
Other views:
- DBA_TAB_PARTITIONS
 - ALL_TAB_PARTITIONS
 - USER_TAB_PARTITIONS
 
Sequence creation
Sequence usage sample
   1 -- table creation
   2 CREATE TABLE Employee 
   3 ( idEmployee number(12), name varchar2(255), lastName varchar2(255),
   4 constraint pkIdEmployee PRIMARY KEY(idEmployee)
   5 );
   6 -- sequence creation
   7 CREATE SEQUENCE seqEmplyee 
   8 start with 1 increment by 1 minvalue 1 maxvalue 65536;
   9 -- insert values
  10 INSERT INTO Employee (idEmployee,name,lastName) 
  11 values(seqEmplyee.nextval,'Bart','Simpson'); 
  12 INSERT INTO Employee (idEmployee,name,lastName) 
  13 values(seqEmplyee.nextval,'Peter','Griffin'); 
  14 INSERT INTO Employee (idEmployee,name,lastName) 
  15 values(seqEmplyee.nextval,'Homer','Simpson'); 
  16 -- check sequence current value
  17 SELECT seqEmplyee.currval FROM dual;
User and table space creation in Oracle XE
   1 -- login with system user
   2 create tablespace christs datafile 'c:\christs.dbf' size 100m;
   3 create user chris identified by 12345678 default tablespace christs;
   4 alter user chris quota unlimited on christs;
   5 grant create session to chris;
   6 grant create table to chris;
   7 
   8 -- login with user chris
   9 create table CHRIS.test ( name varchar(255) ) tablespace chris;
  10 insert into CHRIS.test (name) values('Test name 1234');
  11 
  12 -- login with system user
  13 -- user alice to just run selects
  14 create user alice identified by 12345678 default tablespace christs;
  15 grant create session to alice;
  16 grant select on CHRIS.test to alice;
  17 
  18 -- login with alice
  19 select * from CHRIS.test;
Oracle Database 11g Express Edition
Download from Oracle site
- Run setup.exe
 - Next
 - Accept
 - Next
 - c:\oraclexe
 - Port TNS 1521
 - Port MTS 2030
 - Port Http 8081
 - Next
 - For user sys and system password ********
 - Next
 - Install
 - Finish
 
Info
- Default SID xe .
 - Default JDBC driver JAR ojdbc6.jar .
 - JDBC Url jdbc:oracle:thin:@//localhost:1521/XE
 
Returning a JDBC result set from an Oracle stored procedure
http://enterprisedt.com/publications/oracle/result_set.html
Create function:
Test function:
JDBC invocation
   1 //String query = "begin ? := sp_get_stocks(?); end;";
   2 //JDBC syntax
   3 String query = "{ call ? := sp_get_stocks(?) }";
   4 
   5 CallableStatement stmt = conn.prepareCall(query);
   6 
   7 // register the type of the out param - an Oracle specific type
   8 stmt.registerOutParameter(1, OracleTypes.CURSOR);
   9 
  10 // set the in param
  11 stmt.setFloat(2, price);
  12 
  13 // execute and retrieve the result set
  14 stmt.execute();
  15 ResultSet rs = (ResultSet)stmt.getObject(1);
  16 
  17 // print the results
  18 while (rs.next()) {
  19     System.out.println(rs.getString(1) + "\t" +
  20         rs.getFloat(2) + "\t" +
  21         rs.getDate(3).toString());
  22 }
http://docs.oracle.com/cd/E18283_01/appdev.112/e13995/oracle/jdbc/OracleCallableStatement.html
   1 // SQL92 syntax
   2   CallableStatement cs1 = conn.prepareCall
   3   ( "{call proc (?,?)}" ) ; // stored proc
   4   CallableStatement cs2 = conn.prepareCall
   5   ( "{? = call func (?,?)}" ) ; // stored func
   6   // Oracle PL/SQL block syntax
   7   CallableStatement cs3 = conn.prepareCall
   8   ( "begin proc (?,?); end;" ) ; // stored proc
   9   CallableStatement cs4 = conn.prepareCall
  10   ( "begin ? := func(?,?); end;" ) ; // stored func
  11 
http://www.informit.com/articles/article.aspx?p=26251&seqNum=6
   1 CREATE OR REPLACE PROCEDURE p_highest_paid_emp
   2        (ip_deptno NUMBER,
   3        op_empno OUT NUMBER,
   4        op_ename OUT VARCHAR2,
   5        op_sal OUT NUMBER)
   6 IS
   7  v_empno NUMBER;
   8  v_ename VARCHAR2(20);
   9  v_sal NUMBER;
  10 BEGIN
  11  SELECT empno, ename, sal
  12  INTO v_empno, v_ename, v_sal
  13  FROM emp e1
  14  WHERE sal = (SELECT MAX(e2.sal)
  15      FROM emp e2
  16      WHERE e2.deptno = e1.deptno
  17      AND e2.deptno = ip_deptno)
  18   AND deptno = ip_deptno;
  19  op_empno := v_empno;
  20  op_ename := v_ename;
  21  op_sal := v_sal;
  22 END;
  23 /
   1 import java.sql.*;
   2 
   3 public class StProcExample {
   4  public static void main(String[] args)
   5  throws SQLException {
   6 int ret_code;
   7 Connection conn = null;
   8  try {
   9   //Load and register Oracle driver
  10   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  11  //Establish a connection
  12 
  13  conn = DriverManager.getConnection("jdbc:oracle:thin:@training:1521:
  14  Oracle", "oratest", "oratest");
  15  int i_deptno = 10;
  16  CallableStatement pstmt = conn.prepareCall("{call p_highest_
  17  paid_emp(?,?,?,?)}");
  18  pstmt.setInt(1, i_deptno);
  19  pstmt.registerOutParameter(2, Types.INTEGER);
  20  pstmt.registerOutParameter(3, Types.VARCHAR);
  21  pstmt.registerOutParameter(4, Types.FLOAT);
  22  pstmt.executeUpdate();
  23 
  24  int o_empno = pstmt.getInt(2);
  25  String o_ename = pstmt.getString(3);
  26  float o_sal = pstmt.getFloat(4);
  27  System.out.print("The highest paid employee in dept "
  28  +i_deptno+" is: "+o_empno+" "+o_ename+" "+o_sal);
  29  pstmt.close();
  30  conn.close();
  31   } catch (SQLException e) {ret_code = e.getErrorCode();
  32    System.err.println(ret_code + e.getMessage()); conn.close();}
  33  }
  34 }
http://oracle-base.com/articles/misc/using-ref-cursors-to-return-recordsets.php
   1 import java.sql.*;
   2 import oracle.jdbc.*;
   3 
   4 public class TestResultSet  {
   5   public TestResultSet() {
   6     try {
   7       DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
   8       Connection conn = DriverManager.getConnection("jdbc:oracle:oci:@w2k1", "scott", "tiger");
   9       CallableStatement stmt = conn.prepareCall("BEGIN get_emp_rs(?, ?); END;");
  10       stmt.setInt(1, 30); // DEPTNO
  11       stmt.registerOutParameter(2, OracleTypes.CURSOR); //REF CURSOR
  12       stmt.execute();
  13       ResultSet rs = ((OracleCallableStatement)stmt).getCursor(2);
  14       while (rs.next()) {
  15         System.out.println(rs.getString("ename") + ":" + rs.getString("empno") + ":" + rs.getString("deptno")); 
  16       }
  17       rs.close();
  18       rs = null;
  19       stmt.close();
  20       stmt = null;
  21       conn.close();
  22       conn = null;
  23     }
  24     catch (SQLException e) {
  25       System.out.println(e.getLocalizedMessage());
  26     }
  27   }
  28 
  29   public static void main (String[] args) {
  30     new TestResultSet();
  31   }
  32 }
Exceptions
Convert to date
TO_DATE('2013/07/19', 'yyyy/mm/dd')
Result: date value of July 19, 2013
TO_DATE('071913', 'MMDDYY')
Result: date value of July 19, 2013
TO_DATE('20120311', 'yyyymmdd')
Result: date value of Mar 11, 2012
Number updated rows
- SQL%ROWCOUNT
 - numberRows := SQL%ROWCOUNT;
 
Return first non null expression
- use NVL function , Oracle specific
 - use COALESCE function , ANSI 92
 
   1 UPDATE xyz set fieldx = COALESCE(fieldx_param, fieldx) where idx=idx_p;
Get unique identifier GUID
https://docs.oracle.com/cd/B12037_01/server.101/b10759/functions153.htm
SYS_GUID generates and returns a globally unique identifier (RAW value) made up of 16 bytes. On most platforms, the generated identifier consists of a host identifier, a process or thread identifier of the process or thread invoking the function, and a nonrepeating value (sequence of bytes) for that process or thread.
   1 select sys_guid() from dual;
Data types
- number
 - nvarchar2
 - int
 - real
 
Limit number of rows (rownum)
Docker container Oracle DB XE 21c
Should have oracle-database-xe-21c-1.0-1.ol8.x86_64.rpm in the same folder of the Dockerfile and steps.sh file.
Dockerfile
steps.sh
   1 #!/bin/sh
   2 yum update -y
   3 yum install -y oracle-database-preinstall-21c
   4 yum -y localinstall /mnt/oracle-database-xe-21c-1.0-1.ol8.x86_64.rpm
   5 echo -e "TestOracle01\nTestOracle01\n" | /etc/init.d/oracle-xe-21c configure
   6 echo "PATH=/opt/oracle/product/21c/dbhomeXE/bin/:$PATH" >> ~/.bashrc
   7 echo "export ORACLE_HOME=/opt/oracle/product/21c/dbhomeXE/" >> ~/.bashrc
Steps
   1 docker build -t oracledb_test .
   2 docker run --rm -dit --name oraclelinux -p 1521:1521 -v $PWD:/mnt/ -e ORACLE_DOCKER_INSTALL=true oracledb_test 
   3 docker exec -it oraclelinux bash
   4 cd /mnt/
   5 time sh steps.sh # real 24m43.345s
   6 source ~/.bashrc
   7 sqlplus system/TestOracle01@localhost/xe
   8 SELECT table_name  FROM dba_tables;
   9 exit
