我有数据库TNSEntries
的详细信息。我需要用Java编写代码来检查TNSPING
。反正有吗?
示例TNSENtry
:
orcldb=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = myhost)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = myservice)
(INSTANCE_NAME = myinstance)
)
)
我使用jdbc oracle驱动程序使用用户名和密码进行了oracle连接。这个TNSPING对我来说是新的,它没有用户名和密码。你能帮助任何人帮忙在java中编写TNSPING吗?
答案 0 :(得分:2)
TNSPING仅验证与Listener进程的网络连接,您无需传递用户名和密码。
正如@ KonstantinV.Salikhov所说,您可以编写如下工具的代码,它将验证:
.-与侦听程序进程的网络连接(如果侦听器是UP或不像TNSPING那样) .-数据库服务是否为UP(因为TNSPING将识别数据库服务名称)。
该工具不会使用用户名/密码,因为我们只需要登录失败事件来验证数据库已启动并正在运行。
JAVA CODE:
import java.sql.*;
import oracle.jdbc.pool.*;
public class ThinTnsnames {
static String sql = null;
public static void main(String[] args) {
String entry_name = args [0];
test (entry_name);
}
public static void test (String entry_name) {
Connection pconnection = null;
try {
String l_url = "jdbc:oracle:thin:@" + entry_name;
System.out.println( "Connection string = " + l_url );
OracleDataSource ods = new OracleDataSource();
ods.setURL(l_url);
pconnection = ods.getConnection ();
}
catch(SQLException e) {
int errorCode = e.getErrorCode() ;
System.err.println("Error Code: " + errorCode) ;
if ( errorCode == 12514 ) {
System.err.println("Listener is UP but database is DOWN");
}
if ( errorCode == 17002 ) {
System.err.println("Listener is DOWN");
}
if ( errorCode == 1017 ) {
System.err.println("Listener is UP and database is UP");
}
// e.printStackTrace();
}
finally {
try {
if (pconnection != null )pconnection .close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
您可以在另一个目录中使用自己的tnsnames.ora文件进行测试,例如在“/ home / oracle / 2”目录中:
[oracle@ora12c 2]$ cat /home/oracle/2/tnsnames.ora
orcldb =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ora12c.node.com)(PORT = 15300))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = db02.node.com)
(INSTANCE_NAME = db02)
)
)
然后你用这种方式调用它:
export JAVA_HOME=/opt/java/jdk1.7.0_71
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=/home/oracle/2/ojdbc7.jar:.
java -Doracle.net.tns_admin=/home/oracle/2 ThinTnsnames orcldb
可能的输出是:
Connection string = jdbc:oracle:thin:@orcldb
Error Code: 1017
Listener is UP and database is UP
Connection string = jdbc:oracle:thin:@orcldb
Error Code: 12514
Listener is UP but database is DOWN
Connection string = jdbc:oracle:thin:@orcldb
Error Code: 17002
Listener is DOWN
您可以通过查询dba_audit_trail视图来验证连接期间没有使用用户名,如下所示:
select username,action_name,returncode from dba_audit_trail
where action_name like 'LOG%' ;
USERNAME ACTION_NAME RETURNCODE
-------------------- ---------------------------- ----------
LOGON 1017