Article turned from: http://blog.itpub.net/22664653/viewspace-1383092/
Objective
This article is a learning note to learn how to connect to Oracle through Java JDBC/OJDBC in several ways.
One use method
Method One: Connect to Oracle using SERVICE_NAME
Example: Jdbc:oracle:thin:@//10.10.10.1:1521/tdb
Note The format here, which is followed by//, which is the main difference from using SIDS.
For a cluster, the SID for each node is different, but the service_name can contain all nodes.
method Two: Use SID to connect to Oracle
Note that this method has not been recommended, and Oracle recommends using SERVICE_NAME
Method Three: Connect Oracle using Tnsname
Example:jdbc:oracle:thin: @TESTDB
Two source code
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
Public class TestDB {
Public Static String Dbdriver = "oracle.jdbc.driver.OracleDriver";
Public Static String Dburl = "jdbc:oracle:thin:@127.0.0.1:1521/testdb1"; Sid format Testdb1 is SID
Public Static String Dburl = "jdbc:oracle:thin:@//127.0.0.1:1521/tdb"; ServiceName TDB is service_name
Public Static String DBUSER = "test\";
Public Static String Dbpassword = \ "xxx\";
Public Static String Dburl = \ "jdbc:oracle:thin: @TESTDB \";//tnsname format
Public static void Main (String[] args) throws Exception
{
Connection con = null;
PreparedStatement PS = null;
ResultSet rs = null;
String strSQL = \ "Select COUNT (*) from tsa_dim_deal\";
# System.setproperty (\ "oracle.net.tns_admin\", \ "/home/admin/oracle\");//When using the Tnsname method You need to make the absolute path to the folder where the Tnsname.ora
Class. forname (Dbdriver). newinstance ();
con = drivermanager.getconnection (Dburl,dbuser,dbpassword);
PS = con.preparestatement (strSQL);
rs = Ps.executequery ();
while (Rs. Next ())
{
System.out.println (\ "num:\" +rs.getstring (1));
}
Rs.close ();
Ps.close ();
Con.close ();
}
}
Appendix:
[Email protected] oracle]$ more Tnsnames.ora
testdb=
(DESCRIPTION =
on)
(Address_list =
(ADDRESS = (PROTOCOL = TCP) (HOST = 10.10.10.1) (PORT = 1521))
(ADDRESS = (PROTOCOL = TCP) (HOST = 10.10.10.2) (PORT = 1521))
(ADDRESS = (PROTOCOL = TCP) (HOST = 10.10.10.3) (PORT = 1521))
(ADDRESS = (PROTOCOL = TCP) (HOST = 10.10.10.4) (PORT = 1521))
(ADDRESS = (PROTOCOL = TCP) (HOST = 10.10.10.5) (PORT = 1521))
(ADDRESS = (PROTOCOL = TCP) (HOST = 10.10.10.6) (PORT = 1521))
)
(Connect_data =
(SERVER = dedicated)
(service_name = TDB)
)
)
Note that the service_name TDB and Tnsname (TESTDB) are intentionally set differently in this article.
Three references:
Http://razorsql.com/docs/help_oracle.html
JDBC/OJDBC three Ways to link Oracle (GO)