Created
October 15, 2021 16:32
-
-
Save diegofcornejo/7fe1b980f779bda83ad303e8351c9893 to your computer and use it in GitHub Desktop.
Java test oracle db connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://dba010.com/2019/09/30/simpe-java-code-to-test-connection-to-oracle-database/ | |
Assuming that client computer does not have Oracle client installed. | |
1. Download necessary version of ojdbc jar file from Oracle. The latest version for now is ojdbc8.jar | |
2. Install java development tools: | |
# yum install java-devel * -y | |
3. Create a sample java code, which: | |
– connects to the database | |
– selects 1 from dual | |
– disconnects | |
# cat JDBCTest.java | |
import java.sql.*; | |
class JDBCTest{ | |
public static void main(String args[]) throws SQLException { | |
Connection con = null; | |
try{ | |
Class.forName("oracle.jdbc.driver.OracleDriver"); | |
String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" + args[0] + ")(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orclgg)))"; | |
System.out.println("jdbcurl=" + dbURL); | |
String strUserID = "system"; | |
String strPassword = "Oracle123"; | |
con=DriverManager.getConnection(dbURL,strUserID,strPassword); | |
System.out.println("Connected to the database."); | |
Statement stmt=con.createStatement(); | |
System.out.println("Executing query"); | |
ResultSet rs=stmt.executeQuery("SELECT 1 FROM DUAL"); | |
while(rs.next()) | |
System.out.println(rs.getInt("1")); | |
con.close(); | |
}catch(Exception e){ System.out.println(e);} | |
finally { | |
con.close(); | |
} | |
} | |
} | |
Advertisements | |
REPORT THIS AD | |
Advertisements | |
REPORT THIS AD | |
4. Compile java code and check that *.class file was generated: | |
# javac JDBCTest.java | |
# ll JDBCTest.* | |
-rw-r--r-- 1 root root 1836 Sep 27 11:45 JDBCTest.class | |
-rw-r--r-- 1 root root 925 Sep 27 11:45 JDBCTest.java | |
5. Run code: | |
# java -Djava.security.egd=file:/dev/../dev/urandom -cp ojdbc8.jar:. JDBCTest "stbyrac-scan.example.com" | |
# java -cp ojdbc8.jar:. JDBCTest | |
jdbcurl=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=stbyrac-scan.example.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orclgg))) | |
Connected to the database. | |
Executing query… | |
1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment