Connection from Selenium Java test script to MySQL database failing - java

I'm trying to connect to a MySQL database using the program below. Depending on how I present the connection string I get the following errors.
IP address separated from 'mysql' by ':' only:
conn = DriverManager.getConnection("jdbc:mysql:[valid ip address]/localhost:3306/[valid database name]","[valid username]","[valid password]");
SQLState: 08001
VendorError: 0
java.sql.SQLException: No suitable driver found for jdbc:mysql:[valid ip address]/localhost:3306/[valid database name]
IP address separated from 'mysql' by ':http://':
conn = DriverManager.getConnection("jdbc:mysql:http://[valid ip address]/localhost:3306/[valid database name]","[valid username]","[valid password]");
SQLState: 08001
VendorError: 0
java.sql.SQLException: No suitable driver found for jdbc:mysql:http://[valid ip address]/localhost:3306/[valid database name]
IP address separated from 'mysql' by '://':
conn = DriverManager.getConnection("jdbc:mysql://[valid ip address]/localhost:3306/[valid database name]","[valid username]","[valid password]");
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
SQLState: 08S01
VendorError: 0
In the latter instance a stacktrace provides 'Caused by: java.net.ConnectException: Connection refused: connect'
In all cases the stacktrace also indicates that the line of code setting the variable 'conn' is throwing the exception.
Note that in the program listing text within square brackets represents obfuscated code and that the brackets are not actually in the program.
My question is, do I actually have the required drivers installed or not, or is there a problem with my connection string? Could there be some other issue that I haven't thought of?
Code follows
package [package name];
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLConnectionTest
{
#Test
public void startWebDriver()
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
Statement stmt = null;
Connection conn = null;
ResultSet rs = null;
try
{
conn = DriverManager.getConnection("jdbc:mysql://[valid ip address]/localhost:3306/[valid database name]","[valid username]","[valid password]");
// Do something with the Connection
}
catch (SQLException ex)
{
// handle any errors
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
ex.printStackTrace();
}
try
{
conn.close();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
}
Some information on the environment:
IDE: Eclipse Luna Service Release 2 (4.4.2), Build id: 20150219-0600
jre System Library: jre1.8.0_45
MySQLConnector library: mysql-connector-java-5.1.36.jar (appears in Referenced Libraries section of Package Explorer)
I've also installed mysql-connector-java-gpl-5.1.36, jdk-8u45-windows-x64 and selenium-java-2.45.0
I'll be happy to provide any further information as required.

The connection process seems OK to me, however there's something strange in the connection URL. You have
conn = DriverManager.getConnection("jdbc:mysql://[valid ip address]/localhost:3306/[valid database name]","[valid username]","[valid password]");
which has IP address and localhost:port. This is not a valid URL, yo have to remove either the localhost or the IP address:
conn = DriverManager.getConnection("jdbc:mysql://[valid ip address]:3306/[valid database name]","[valid username]","[valid password]");
or
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/[valid database name]","[valid username]","[valid password]");
That should do the trick.

Related

Connection to Oracle 11g from network machine fails via java

I have orace 11g running on 192.168.1.217 and I am trying to connect it using JDBC driver with java and it gives me following error
IO Error: The Network Adapter could not establish the connection
Library I am using is ojdbc6.jar
Here is my code
public void makeOracleConnection() {
try {
Class.forName("oracle.jdbc.OracleDriver");
oraCon = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.217:1521:orcl", "hr", "hr");
oraStmt = oraCon.createStatement();
oraRsStmt=oraCon.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
} catch (Exception e) {
System.out.println("Error while making connection with Database : " + e.getMessage());
}
}
I have also tried to ping on 192.168.1.217 then pins is successful.
Also TNSLISTENER is running on that machine.
please help.
Please find print stack trace here
run:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:657)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:560)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at test.oracle.makeOracleConnection(oracle.java:30)
at test.oracle.<init>(oracle.java:21)
at test.oracle.main(oracle.java:69)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:470)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:506)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:230)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496)
... 8 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:163)
at oracle.net.nt.ConnOption.connect(ConnOption.java:159)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:428)
... 13 more
BUILD SUCCESSFUL (total time: 1 second)
You get the error
java.net.ConnectException: Connection refused: connect
Which means that there is nothing listening on the machine and port you are trying to connect to. Your Java code looks correct so I would continue to investigate that Oracle is actually listening on port 1521 on 192.168.1.217.
If you run run netstat -n on the server you should find a line that looks like
TCP [::]:1521 [::]:0 LISTENING
If something really is listening on that port. If you do not find that line, check your Oracle configuration.
Try to connect with some other tool, ie sqlplus to verify that the issue is not with Oracle. If you cannot connect with sqlplus/sql developer, make sure that your oracle is configured to allow remote connections, and also listens on given addresses/ports
public void makeOracleConnection() {
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection oraCon = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.217:1521:orcl", "hr", "hr");
Statement oraStmt = oraCon.createStatement();
//oraRsStmt=oraCon.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
ResultSet rs = oraStmt.executeQuery("select hello as result from dual");
while(rs.next()) {
System.out.println(rs.getString("result"));
}
}
catch (Exception e)
System.out.println("Error while making connection with Database : " + e.getMessage());
}
}
Try this out. Hope it'll help. I also don't like your connection path. Is it right? I think it should be something like this:
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=YES)(ADDRESS=(PROTOCOL=tcp)(HOST=ip adres)(PORT=port)))(CONNECT_DATA=(SERVICE_NAME = orcl)))","username","password"

Local PostgreSQL refusing connection with IntelliJ IDEA

A week ago I installed PostgreSQL with Homebrew following this tutorial. Everything worked fined and I was perfectly able to connect to the database in my Java Example Project. Two days ago, I've tried to see the code again and Java is throwing the following error:
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:239)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:127)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:41)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:414)
at org.postgresql.Driver.connect(Driver.java:282)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.company.Main.main(Main.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.postgresql.core.PGStream.<init>(PGStream.java:61)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:121)
... 16 more
At the beginning I've thought postgresql just stopped listening the port, but it is listening:
$ lsof -i :5432
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
postgres 39225 barbarity 5u IPv6 0x4ef6e84c8de72f23 0t0 TCP localhost:postgresql (LISTEN)
postgres 39225 barbarity 6u IPv4 0x4ef6e84ca3a79493 0t0 TCP localhost:postgresql (LISTEN)
And also I can connect from both PGAdmin and PSQL:
$ psql -d prakt -U barbarity
psql (9.4.2)
Type "help" for help.
prakt=#
Then I tried to uninstall and reinstall from homebrew, but it didn't work neither. I've also tried Postgress.app and nothing also.
Do you have any ideas?
I'm using:
Java SDK 1.8
JDBC 41
PostgreSQL 9.4.2
IntelliJ IDEA 14.1.3
(I put the java code just in case, but it was working a week ago)
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String query = new StringBuilder()
.append("SELECT * FROM customer WHERE id_customer = ? or f_name = ?").toString();
try (Connection connection = DriverManager.getConnection("jdbc:postgresql:prakt", "barbarity", "");
PreparedStatement preparedStatement = connection.prepareStatement(query);){
preparedStatement.setInt(1, 1);
preparedStatement.setString(2,"Richard");
try (ResultSet resultSet = preparedStatement.executeQuery();){
while (resultSet.next()) {
System.out.println(new StringBuilder()
.append("Name: ")
.append(resultSet.getString(2))
.toString());
}
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

ORA-12505, TNS:listener does not currently know of SID

I'm new to java oracle database coding and I'm getting this error when running the code below (eclipse kepler):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class main {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#10.0.32.166:1521:orcl", "username", "password");
} catch (SQLException e) {
e.printStackTrace();
return;
}
}
}
Error is for ojdbc14.jar:
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:389)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:454)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:802)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at oracle.main.main(main.java:18)
While I tried to change ojdbc6.jar but a different error shows up:
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:480)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:413)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at oracle.main.main(main.java:18)
Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:361)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:966)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:292)
... 7 more
Reason I'm experimenting on the 2 jar is I'm not sure which is compatible to jdk 1.6 as this is were I'm gonna deploy (linux env) the executable jar once completed. Need help to identify what these errors are and ideas to fix them? thank you
You do not have a database "called" orcl on the database server 10.0.32.166 with an oracle listener running on port 1521.
Do lsnrctl statusfrom the console on server 10.0.32.166 and see if you have a line like Service "ORCL" has X instance(s). If you don't have that make sure the database is up and you have the correct SID and it is using the listener on port 1521.

informix jdbc stuck connecting

I'm trying to connect to a Informix database server with jdbc using the standard way :
connection = DriverManager.getConnection("jdbc:informix-sqli://"+ip+
/"+sid+":INFORMIXSERVER="+server+";user="+user+";password="+pass+"");
But it keeps trying to connect and does not throw a error message (I suppose it tries to connect because it does not show anything). I'm using IBM Informix driver 4.10.00.1534 and Java 1.7.
I have been using this method to connect to Informix servers until now, in fact it only fails with one server. I can connect to this server through Informix clients with odbc but it keeps failing with jdbc with no error message.
Is there any method to verbose the jdbc connection? Any suggestion about why it fails?
UPDATE: The sqlidebug trace:
C->S (4)
SQ_VERSION
SQ_EOT
S->C (14)
SQ_VERSION
"7.31.TD6" [8]
SQ_EOT
C->S (66)
SQ_INFO
INFO_ENV
Name Length = 12
Value Length = 8
"DBTIME"="%d/%M/%Y"
"DBTEMP"="/tmp"
"SUBQCACHESZ"="10"
INFO_DONE
SQ_EOT
S->C (2)
SQ_EOT
C->S (16)
SQ_DBOPEN
"database" [8]
NOT EXCLUSIVE
SQ_EOT
S->C (28)
SQ_DONE
Warning..: 0x15
# rows...: 0
rowid....: 0
serial id: 0
SQ_COST
estimated #rows: 1
estimated I/O..: 1
SQ_EOT
C->S (78)
SQ_PREPARE
# values: 0
CMD.....: "select site from informix.systables where tabname = ' GL_COLLATE'" [65]
SQ_NDESCRIBE
SQ_WANTDONE
SQ_EOT
And the jdbctrace.log says:
trying com.informix.jdbc.IfxDriver
SQLWarning: reason(Database selected) SQLState(01I04)
SQLWarning: reason(Float to decimal conversion has been used) SQLState(01I05)
SQLWarning: reason(Database has transactions) SQLState(01I01)
SQLWarning: reason(Database selected) SQLState(01I04)
SQLWarning: reason(Database has transactions) SQLState(01I01)
SQLWarning: reason(Database selected) SQLState(01I04)
Try to run code that connects do Informix database but also shows full exception info and create trace files. One trace file is for JDBC, one is for Informix. Change URL to database, username and password, and run it. You will probably see the problem on screen or in trace file:
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
class informix_trace
{
public static void main(String[] args)
{
try
{
Class.forName("com.informix.jdbc.IfxDriver");
FileWriter fwTrace = new FileWriter("c:\\JDBCTrace.log");
PrintWriter pwTrace = new PrintWriter(fwTrace);
DriverManager.setLogWriter(pwTrace);
String debug_url = "SQLIDEBUG=C:\\sqlidebug.trace";
String url = "jdbc:informix-sqli://1.2.3.4:9088/test_db:informixserver=ol_testifx;DB_LOCALE=pl_PL.CP1250;CLIENT_LOCALE=pl_PL.CP1250;charSet=CP1250;" + debug_url
Connection connection = DriverManager.getConnection(url, "user", "passwd");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT FIRST 1 DBINFO('version','full') FROM systables;");
while (resultSet.next())
System.out.println(resultSet.getObject(1));
}
catch (Exception e)
{
e.printStackTrace();
}
}
} // class informix_trace
Informix trace file will be with some postfix (timestamp or similar info) and in my case it was something like sqlidebug.trace1391758523500.0. It is binary but you can analyze it using sqliprt utility.
Example of my session with wrong database name:
c:\>sqliprt sqlidebug.trace1391758523500.0
SQLIDBG Version 1
...
S->C (12)
SQ_ERR
SQL error..........: -329
ISAM/RSAM error....: -111
Offset in statement: 0
Error message......: "" [0]
SQ_EOT
In JDBCTrace.log I can found more interesting info (I see it also on my screen):
SQLState(IX000) vendor code(-111)
java.sql.SQLException: ISAM error: no record found.
at com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:413)
at com.informix.jdbc.IfxSqli.E(IfxSqli.java:3412)
at com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java:2324)
....
at java.sql.DriverManager.getConnection(Unknown Source)
at informix_trace.main(informix_trace.java:20)
getConnection failed: java.sql.SQLException: No database found or wrong system privileges.
(I have translated it from Polish so it can be little different)
My suggestion is to:
build ConnectString and show us its full content, this way we will see if in ip there is only IP address or if it is with port number
instead of adding username and password to ConnectString use 3 parameter version of getConnection() just like:
getConnection("jdbc:informix-sqli://169.0.5.10:9088/test_db:informixserver=ol_test;DB_LOCALE=pl_PL.CP1250;CLIENT_LOCALE=pl_PL.CP1250;charSet=CP1250", username, password)
(of course set your own locale instead of my Polish locale)
To spy network traffic use tools like Wireshark. Start capturing ip traffic to your Informix database. In my case Wireshark rule is:
ip.addr == 169.0.5.10
If I set up wrong IP Wireshark will display "Destination unreachable".
You can also see someting using netstat:
c:\>netstat -an | grep 9088
TCP 169.0.1.126:4295 169.0.5.10:9088 TIME_WAIT
It was when my application stopped working.
In case of error (wrong IP port) I see:
c:\>netstat -an | grep 9089
TCP 169.0.1.126:4398 169.0.5.10:9089 SYN_SENT
IBM says that: From version 3.00.JC1 of IBM® Informix® JDBC Driver onwards, debug drivers are no longer shipped.
Informix JDBC Driver now supports SQLIDEBUG. You no longer need to set values for TRACE, TRACEFILE or PROTOCOLTRACE, PROTOCOLTRACEFILE. You only need to set SQLIDEBUG. and the page goes on to outline the steps you need to create a trace. Copying:
Set the CLASSPATH to the Informix JDBC Driver package.
c:\Infx\Java>set
CLASSPATH=C:\infx\JDBC3.00JC3\lib\ifxjdbc.jar;C:\infx\JDBC3.00JC3\lib\ifxjdbcx.jar;.
Compile simple.java
c:\Infx\Java>javac simple.java
Ensure that SQLIDEBUG is set correctly
c:\Infx\Java>grep SQLIDEBUG simple.java
conn=DriverManager.getConnection("jdbc:informix-sqli://irk:1526/sysmaster:INFORMIXSERVER=irk940;USER=informix;
PASSWORD=ximrofni;SQLIDEBUG=C:\infx\java\trace");
Note: SQLIDEBUG is set in the connection string. It points to where
the trace file will be found with a certain format i.e.
trace.xxxxxxx
Remove or move all other trace files
c:\Infx\Java>del trace*
Run java.simple
c:\Infx\Java>java simple systables syscolumns ... ...
oledbordinals
Then locate the trace file
c:\Infx\Java>dir trace* Volume in drive C has no label. Volume
Serial Number is B823-46D8
Directory of c:\Infx\Java
04/04/2006 14:12 20,560 trace1144156355642.0 1 File(s) 20,560 bytes
0 Dir(s) 4,067,995,648 bytes free
c:\Infx\Java>
You will be able to see that a trace file has been created however
you will not be able to read the file.
Send the trace file to your local technical support office for
analysis.
Of course, if you're not using Version 3.00.JC1 of the Informix drivers, ignore the above and follow a different set of instructions; again duplicated for your convenience:
To turn on tracing, specify the environment variables TRACE,
TRACEFILE, PROTOCOLTRACE, and PROTOCOLTRACEFILE in the database URL or
the property list when you establish a connection to an Informix
database or database server. TRACE can be set to one of the following
levels:
Tracing not enabled. This is the default value.
Traces the entry and exit points of methods.
Same as Level 1, plus generic error messages are also traced.
Same as Level 2, plus data variables are also traced. TRACEFILE Specifies the full pathname of the operating system file on the client
computer to which the TRACE messages are written.
PROTOCOLTRACE traces the SQLI protocol messages sent between your Java
program and the Informix database server.
Can be set to the following levels:
Protocol tracing not enabled. This is the default value.
Traces message IDs.
Same as Level 1, plus the data in the message packets are also traced. PROTOCOLTRACFILE specifies the full pathname of the operating
system file on the client computer to which the PROTOCOLTRACE messages
are written.
Hope that helps
try different jdbc version
check NETTYPE configuration parameter and compare it with current number of informix sessions
dump java thread states (kill -3 ) when jdbc connection hangs
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.informix.*;
public class DBConnect {
static String url="jdbc:informix-sqli://host_name:port/database_name:INFORMIXSERVER=server;user=username;password=password";
public static void main(String [] args){
try {
Class.forName("com.informix.jdbc.IfxDriver");
}catch (Exception e){
System.out.println("ERROR: failed to load Informix JDBC driver.");
e.printStackTrace();
return;
}
try{
DriverManager.registerDriver((com.informix.jdbc.IfxDriver)Class.forName("com.informix.jdbc.IfxDriver").newInstance());
}catch(Exception ex){
System.out.println("Driver is not Registered");
}
try{
Connection conn = DriverManager.getConnection(url);
System.out.println("Connection Successful");
}catch (SQLException e){
System.out.println("ERROR: failed to connect!");
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
return;
}
}
}
For more info go through [this book] (http://www.cursor-distribution.de/aktuell.11.70.xC6/documentation/ids_jdbc_bookmap.pdf)
The problem I encountered was that Informix was listening on local IPv6 address on port 7360, command netstat -a was displaying this format :
TCP [feab::11ab:78ab:efab:8aab%17]:7360 myhostname:0 LISTENING
Therefore my jdbc connection was always failing until I figured out I should have use the IPv6 address in the URL :
jdbc:informix-sqli://fe80::1125:78c0:ef17:8ab5%17:7360:user=informix;password=test;INFORMIXSERVER=ol_informix1210_2
You can test that the connection is working with this simple script :
/***************************************************************************
*
* Title: SimpleConnection.java
*
* Description: Demo a connection to a server (no database specified)
*
* An example of running the program:
*
* java SimpleConnection
* 'jdbc:informix-sqli://myhost:1533:user=<username>;password=<password>'
*
* Expected result:
*
* >>>Simple Connection test.
* URL = "jdbc:informix-sqli://myhost:1533:user=<username>;password=<password>"
* >>>End of Simple Connection test.
*
***************************************************************************
*/
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SimpleConnection {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("FAILED: connection URL must be provided in order to run the demo!");
return;
}
String url = args[0];
String testName = "Simple Connection";
Connection conn = null;
System.out.println(">>>" + testName + " test.");
System.out.println("URL = \"" + url + "\"");
try {
Class.forName("com.informix.jdbc.IfxDriver");
} catch (Exception e) {
System.out.println("FAILED: failed to load Informix JDBC driver.");
}
try {
PrintWriter out = new PrintWriter(System.out, true);
DriverManager.setLogWriter(out);
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("FAILED: failed to connect!");
}
try {
conn.close();
} catch (SQLException e) {
System.out.println("FAILED: failed to close the connection!");
}
System.out.println(">>>End of " + testName + " test.");
}
}

Connecting to remote Mapr Hive via JDBC

This question is similar, but not the same, as Hive JDBC getConnection does not return . Yet this is about a remote connection. Also the metastore is present in the directory in which the hiveserver2 was started.
We have a running mapr cluster on a remote machine. I would like to connect to Hive on this cluster using Java JDBC.
Hence we started the hive server:
/opt/mapr/hive/hive-0.11/bin/hiveserver2
The output of the server process does not contain any error messages. It listens on port 10000 as reported by netstat.
I try to connect to the server as described in https://cwiki.apache.org/confluence/display/Hive/HiveClient, thereby replacing localhost by the server name where the hiveserver2 is running:
Connection con =
DriverManager.getConnection("jdbc:hive://myserver.example.com:10000/default", "", "");
Yet the program hangs exactly at this statement. It does not seem to get a connection.
Possibly I need to supply a username and password?
Initially I had used the driver org.apache.hadoop.hive.jdbc.HiveDriver.
Yet it seems like I should be using the driver org.apache.hive.jdbc.HiveDriver if the hive2 server is running. Now I am getting the following Exception:
Exception in thread "main" java.sql.SQLException: Could not establish connection to jdbc:hive2://myserver.example.com:10000/default: Required field 'client_protocol' is unset! Struct:TOpenSessionReq(client_protocol:null)
at org.apache.hive.jdbc.HiveConnection.openSession(HiveConnection.java:246)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:132)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at HiveJdbcClient.main(HiveJdbcClient.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.apache.thrift.TApplicationException: Required field 'client_protocol' is unset! Struct:TOpenSessionReq(client_protocol:null)
at org.apache.thrift.TApplicationException.read(TApplicationException.java:108)
at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:71)
at org.apache.hive.service.cli.thrift.TCLIService$Client.recv_OpenSession(TCLIService.java:144)
at org.apache.hive.service.cli.thrift.TCLIService$Client.OpenSession(TCLIService.java:131)
at org.apache.hive.jdbc.HiveConnection.openSession(HiveConnection.java:237)
... 10 more
I had the same problem and was able to get around it by adding the correct dependency to my pom.xml file. I was getting the latest apache release of hive from maven central and switched to using the cdh4 release from the cloudera repo. So, what you are seeing may be a symptom of having the wrong hive-jdbc dependency. Here's the maven snippet I added to my pom file:
<repository>
<id>cloudera</id>
<url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
</repository>
...
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>0.10.0-cdh4.3.2</version>
</dependency>
Here's a link about the cloudera repo.
Also, adding the ";auth=noSasl" to the URL made my application hang so I removed it.
I think you need to specify the username. Also itshould be hive2 not hive since you are using hiveserver2.
Try modifying your connection url:
Connection con =
DriverManager.getConnection("jdbc:hive2://myserver.example.com:10000/default", "<user>", "");
Its given in the link Hive2
Hope this helps...!!!
I also had same problem.
Please check if server is reachable on the port 10000 from the client (server and port are enabled no firewall is restricting) also check hiveserver is up and running. if yes then it should work.
following code work for me for mapr hive.
if you have any query related mapr, please refer answers.mapr.com, this contain most of the information which you might be requiring.
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
import org.apache.log4j.Logger;
import java.io.*;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.*;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.*;
public class HiveJdbcClient {
//private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
/**
* #param args
* #throws SQLException
**/
private static Logger mLogger = Logger.getLogger(HiveJdbcClient.class);
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
HiveJdbcClient myJob = new HiveJdbcClient();
myJob.execute();
}
public void execute() throws SQLException {
//mLogger.info("Start HiveJob");
System.out.println("Start HiveJob");
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://myserver:10000/default", "", "");
Statement stmt = con.createStatement();
String sql = "SHOW TABLES";
//String tableName = "testHiveDriverTable";
// ResultSet res1 = stmt.executeQuery("create table " + tableName + " (key int, value string)");
System.out.println("Running: " + sql);
ResultSet res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(res.getString(1));
}
//mLogger.info("HiveJob executed!");
System.out.println("HiveJob executed!");
}
}
You can use the beeline client to connect to hive using JDBC.
It would be some thing like: beeline !connect jdbc:hive2://localhost:10000
check the link:
http://dwbitechguru.blogspot.ca/2014/11/how-to-connect-to-hadoop-hive-using.html
In my case adding the: ;auth=noSasl to the JDBC connect string solved the endless waiting for the connection !
jdbc:hive2://server:10000/default;auth=noSasl
You should get hive-service-X.XX.X-cdhX.X.X.jar here :https://repository.cloudera.com/artifactory/cloudera-repos/org/apache/hive/;
It works fine to me.

Categories

Resources