d-h-n.de
Blog about Oracle, Linux..

Connect Oracle database via JDBC

November 29th, 2011 . by admin

JDBC Thin Driver

  • communicate directly with the data source using a standard Java socket
  • is written 100% in Java and hence is platform independent
  • does not require any additional Oracle software on the client
  • driver supports only TCP/IP-based communication

 

Connect using Oracle Think Driver (via OracleDataSource)
String connectURL = "jdbc:oracle:thin:scott/tiger@//192.168.72.129:1521/orcl.mydom.com";
OracleDataSource ds = new OracleDataSource();
ds.setURL(connectURL);
Connection conn = ds.getConnection();

 

Connect using Oracle Think Driver (via DriverManager)
Class.forName("oracle.jdbc.OracleDriver");
String connectURL = "jdbc:oracle:thin:scott/tiger@192.168.72.129:1521:orcl";
Connection conn = DriverManager.getConnection(connectURL);

 

JDBC OCI Driver

  • OCI stands for Oracle Call Interface
  • called a thick driver
  • allows access Oracle database using a 3GL-Language such as C/C++
  • requires the OCI C libraries, Oracle Net libraries
  • until 9i Release 2 required the entire Oracle client installation
  • since 10g optional reqired just Oracle Instant Client

 

Connect using Oracle OCI Driver
String connectURL = "jdbc:oracle:oci:@myorcl";
Connection conn = DriverManager.getConnection (connectURL, "scott", "tiger" );

 

use OCI Driver when:
  • connect to Oracle other than TCP/IP
  • use OCI connection pooling
  • use TAF – Transparent Application Failover
  • when code run in middle tier, application server
  • OCI is faster before 9i, performance is no relevant since 9i verus thin driver

 

use Thin Driver when:
  • too many clients
  • portability

 

Install

Oracle JDBC Driver kann download from:

10g: http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-10201-088211.html

11g: http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html

or you can find it direct in Oracle installation $ORACLE_HOME/jdbc/lib

exm: ojdbc5.jar is nessesary for connetion to Oracle Database 11g and must be in the LIBPATH

- for connection using OCI Driver, Oracle Client or minimal Oracle Instant Client must installed

 

Test Code

package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.pool.OracleDataSource;

public class TestOJDBCConnect {
	static void doShowEmp(Connection conn) throws SQLException {
		ResultSet rset = null;
		Statement stmt = null;
		stmt = conn.createStatement();
		rset = stmt.executeQuery("select empno, ename, job from emp");

		final int COL_EMPNO = 1;
		final int COL_ENAME = 2;
		final int COL_JOB = 3;

		while (rset.next()) {
			int empNo = rset.getInt(COL_EMPNO);
			String empName = rset.getString(COL_ENAME);
			String empJob = rset.getString(COL_JOB);
			System.out.println(empNo + " " + empName + " " + empJob);
		}
		rset.close();
		stmt.close();
	}

	static void doSelect(Connection conn, String sql) throws SQLException{
		Statement stmt = conn.createStatement();
		ResultSet rset = stmt.executeQuery(sql);
		if (rset.next())
			System.out.println(rset.getString(1));
		rset.close();
		stmt.close();
	}

	public static Connection getConnectionByDataSource() throws SQLException {
		String connectURL = "jdbc:oracle:thin:scott/tiger@//192.168.72.129:1521/orcl.mydom.com";
		OracleDataSource ds = new OracleDataSource();
		ds.setURL(connectURL);
		Connection conn = ds.getConnection();
		doSelect(conn, "select 'Connecting via DataSource..User is '|| initcap(USER) from dual");
		return conn;
	}

	public static Connection getConnectionByDriverManager() throws SQLException, ClassNotFoundException {
		Class.forName("oracle.jdbc.OracleDriver");
		String connectURL = "jdbc:oracle:thin:scott/tiger@192.168.72.129:1521:orcl";
		Connection conn = DriverManager.getConnection(connectURL);
		doSelect(conn, "select 'Connecting via DriverManager..User is '|| initcap(USER) from dual");
		return conn;
	}

	public static Connection getConnectionOCI() throws SQLException {
		String connectURL = "jdbc:oracle:oci:@myorcl";
		Connection conn = DriverManager.getConnection (connectURL, "scott", "tiger" );
		doSelect(conn, "select 'Connecting via OCI..User is '|| initcap(USER) from dual");
		return conn;
	}

	public static void main(String args[]) throws SQLException, ClassNotFoundException {
		Connection conn = null;

		conn = getConnectionByDataSource();
		conn.close();

		conn = getConnectionByDriverManager();
		conn.close();

		conn = getConnectionOCI();
		doShowEmp(conn);
		conn.close();
	}
}
  • jdbc:oracle:thin: is the prefix when connect using Thin driver
  • jdbc:oracle:oci: is the prefix when connect using OCI driver
  • scott is username
  • tiger is password
  • 192.168.72.129 is the ip of the database server (or hostname)
  • 1521 ist the port number
  • orcl.mydom.com is the service name
  • orcl is the SID
  • myorcl is the net service name from tnsnames.ora

 
.. the output in Eclipse console is:

Connecting via DataSource..User is Scott
Connecting via DriverManager..User is Scott
Connecting via OCI..User is Scott
7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK
7900 JAMES CLERK
7902 FORD ANALYST
7934 MILLER CLERK

Installing SQLPlus Instant Client

November 23rd, 2011 . by admin

What is SQL*Plus Instant Client?

SQL*Plus Instant Client is a standalone product with all the functionality of SQL*Plus command-line. It connects to existing remote Oracle databases, but does not include its own database. It is easy to install and uses significantly less disk space than the full Oracle Database Client installation required to use SQL*Plus command-line.

 

To install SQLPlus Instant Client take the following steps:

1. Download:

Exm for Client as Windows: http://www.oracle.com/technetwork/topics/winsoft-085727.html

Choosing: Version 11.2.0.1.0

Instant Client Package – Basic: All files required to run OCI, OCCI, and JDBC-OCI applications

instantclient-basic-win32-11.2.0.1.0.zip (51,458,190 bytes)

Instant Client Package – SQL*Plus: Additional libraries and executable for running SQL*Plus with Instant Client

instantclient-sqlplus-win32-11.2.0.1.0.zip (758,913 bytes)

 

2. Extract

Extract the 2 zip file to exm. c:\oracle

C:\oracle\instantclient_11_2

 

3. Configuration:

- Create file tnsnames.ora and place it on C:\oracle\instantclient_11_2, exm:

MYORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.72.129)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl.mydom.com)
    )
  )

 

    - Extend the System Path:

  • Right click the Symbol Computer
  • ->System Properties
  • ->Enviroment Variables
  • ->Choice ‘Path’ in System Variables
  • ->Click Button Edit
  • ->Append ;C:\oracle\instantclient_11_2 in field Variable value
  • ->Click Button OK

 

    - Define new Variable TNS_ADMIN

  • Click Button New
  • ->Input TNS_ADMIN in field Variable name
  • ->Input C:\oracle\instantclient_11_2 in field Variable value
  • -Click Button Ok

 

4. Test

-Open a new CMD

C:\>echo %TNS_ADMIN%
C:\oracle\instantclient_11_2

C:\>echo %PATH%
...C:\oracle\instantclient_11_2;...
C:\>sqlplus /nolog

SQL*Plus: Release 11.2.0.1.0 Production on Wed Nov 23 13:49:30 2011

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

SQL> conn scott/tiger@myorcl
Connected.
SQL> disc
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> conn sys/foo@myorcl as sysdba
Connected.
SQL>

Troubleshooting:

1.check if it’s ok with the network (ping) else you get:

ERROR:
ORA-12170: TNS:Connect timeout occurred

 

2.if the listener is running on the atabase server, else you get:

ORA-12541: TNS:no listener

 

3.if the tnsnames.ora is correct and can be found on path TNS_ADMIN, else you get:

ERROR:
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor

or

ERROR:
ORA-12154: TNS:could not resolve the connect identifier specified

Setup Permalink in WordPress

November 16th, 2011 . by admin

1. Change Setting in WordPress

- Goto Permalink Settings Page: Settings->PermaLinks.

- Input in Field Custom Structur: /%postname%

This make the link of the articles like this, exm:

http://localhost/wordpress/create-database-per-response-file-with-dba

2. Load Apache rewrite_module

Open file httpd.conf looking for:

#LoadModule rewrite_module modules/mod_rewrite.so

change to:

LoadModule rewrite_module modules/mod_rewrite.so

next search this:

    ..
    AllowOverride None
    ...

change to:

    ..
    AllowOverride All
    ...

Stop and Start Apache again!

(Optional you can check per <?php phpinfo(); ?> if the module loaded)

 

3. .htaccess

root directory of wordpress must have a file .htaccess like this:

# BEGIN WordPress

RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
# END WordPress

Default this file is generated by WordPress.


Howto run Oracle SQLs in Linux shell script?

November 9th, 2011 . by admin

1. create a script.sql which contents only SQLs

.. and from Linux script call:

sqlplus /nolog @script.sql

 

2. write SQLs direct in Linux shell script between << EOF..EOF

#!/bin/bash
sqlplus  /nolog <<EOF
connect scott/tiger
SELECT * from  emp where ename='SCOTT';
EOF

The difference between with and without -s

Without -s:

exm. script test.sh

#!/bin/bash
sqlplus  /nolog <<EOF
connect scott/tiger
SELECT * from  emp where ename='SCOTT';
EOF

..and the output is:

[oracle@pc2 scripts]$ ./test.sh 

SQL*Plus: Release 11.2.0.1.0 Production on Mon Oct 24 11:02:58 2011

Copyright (c) 1982, 2009, Oracle.  All rights reserved.

@> Connected.
SCOTT@orcl>
     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20

SCOTT@orcl> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
[oracle@pc2 scripts]$

 

With -s:

exm. script test.sh

#!/bin/bash
sqlplus -s /nolog <<EOF
connect scott/tiger
SELECT * from  emp where ename='SCOTT';
EOF

..and the output is:

[oracle@pc2 scripts]$ ./test.sh 

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20