I'm writing a Java program that queries a PostgreSQL database. I'm following this example and have trouble here:
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/testdb", "mkyong",
"123456");
According to the JavaDoc for DriverManager the first string is "a database url of the form jdbc:subprotocol:subname. When I connect to the server I type in psql -h dataserv.abc.company.com -d app -U emp24 and give the password qwe123 (for example sake). What should the first argument of getConnection be?
I've tried
connection = DriverManager.getConnection(
"jdbc:postgresql://dataserv.abc.company.com", "emp24",
"qwe123");
and get the run time error: no suitable driver found.
I've download JDBC4 Postgresql Driver, Version 9.2-1000.
After I fixed my program to load the driver with Class.forName("org.postgresql.Driver"); it recognises the JDBC URL but it still doesn't connect. I now have a new error.
When I run the program there is an error and here is the output with the stack trace:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
Connection Failed! Check output consoleorg.postgresql.util.PSQLException: Connection 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:207)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:140)
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:31)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:23)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DatabaseConnect.main(DatabaseConnect.java:32)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.postgresql.core.PGStream.<init>(PGStream.java:60)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:101)
... 11 more
I format the URL for the getConnection like this:
"jdbc:postgresql://dataserv.abc.company.com:5432/app"
Most likely you have failed to register the JDBC driver with the DriverManager, so JDBC doesn't know how to handle jdbc:postgresql:. Try Class.forName("org.postgresql.Driver"); before you try to use DriverManager.getConnection. That is shown in the example code you linked to (it's the very first line), is explained in the preamble of the DriverManager documentation, and is also explained in detail in the PgJDBC documentation linked below.
Alternately, maybe you've typo'd jdbc:postgresql: so the DriverManager is looking for a driver named postgrsql or Postgresql or something, which won't be registered.
Finally, you could be swallowing a class loading exception so the driver load fails and you don't see it, like this (extremely bad) code:
// Very bad code, never do this
try {
Class.forName("org.postgresql.Driver");
} catch (ClasNotFoundException ex) {}
Never do the above. Either wrap the exception in an unchecked runtime exception or just add throws ClasNotFoundException to your method definition.
As per the PgJDBC documentation and FAQ, to use the driver you must:
Download the JDBC driver;
Ensure that the JDBC driver is on your CLASSPATH;
Load/register the driver by passing a JVM parameter or using Class.forName("org.postgresql.Driver"); so it's registered with the DriverManager;
Connect to the database
These are all links to the manual.
For more on the CLASSPATH, see wikipedia
The JDBC DriverManager is discussed in the JavaDoc and the JDBC tutorial.
As for the JDBC URL format for PostgreSQL, that's in the documentation too.
With JDBC, a database is represented by a URL (Uniform Resource
Locator). With PostgreSQL™, this takes one of the following forms:
jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
The docs go on to explain what each parameter means and the optional connection parameters.
From this you can see, in answer to your comment on John Woo's answer, that you do not have to specify the port if your server is listening on the default PostgreSQL port, which it is if you don't have to specify the port when connecting with psql.
That makes your getConnection arguments correct, the problem is that you didn't register the driver first.
Make sure your pg_hba.conf file has an entry for local connections, something like this:
local mydatabasename myusername password
Related
I’ve been receiving the following error:
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SQL Server did not return a response. The connection has been closed. ClientConnectionId:be8d9e1d-fff7-4310-ae77-03394c83f86b".
(More of the error at bottom of post)
When trying to connect to a MSSQL database.
I’m using the following connection string:
jdbc:sqlserver://192.168.100.190:1433;databaseName=myDatabase;user=validUser;password=validPassword;encrypt=false;trustServerCertificate=false;sslProtocol=TLSv1;
I’ve tried variations of the connection string, essentially changing and omitting:
encrypt=false;trustServerCertificate=false;sslProtocol=TLSv1;
I’ve tried different versions of the driver from:
https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-2017
all with the same results.
It is important to note that on some PC’s the application connects
and works as expected but I have so far found no real differences
between the PC’s or user accounts, no pattern really.
I’ve tried different versions of the JDK and different JRE’s, all
give the same results.
UPDATE: I have since found JRE 1.8.0_152 works in all my test cases
I’ve tried looking at logs on the servers and there are no entries in
the SQL logs.
If I try a connection string with the wrong credentials, the error is
exactly the same.
I’ve setup a test server and database, this works fine, as does one I
setup in a Virtual Machine.
I can connect to said database using Navicat for example and have
another application, writing in Visual Basic.Net that connects fine,
so it would see that it is just something with this driver or java,
but as I say, it does work on some PC’s and not others and of course
works as expected in my test environment.
Any thoughts or suggestions would be greatly appreciated.
I’ve not provided any code, as I can replicate the exact same results using the example code provided here:
https://learn.microsoft.com/en-us/sql/connect/jdbc/step-3-proof-of-concept-connecting-to-sql-using-java?view=sql-server-2017
More detail on error:
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SQL Server did not return a response. The connection has been closed. ClientConnectionId:be8d9e1d-fff7-4310-ae77-03394c83f86b".
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2670)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1837)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2257)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1921)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1762)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1077)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:623)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at database.DataBase.openConnection(DataBase.java:122)
at jambuddylite.jblCoord.readSimex(jblCoord.java:387)
at jambuddylite.jblCoord$2.run(jblCoord.java:314)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: SQL Server did not return a response. The connection has been closed. ClientConnectionId:be8d9e1d-fff7-4310-ae77-03394c83f86b
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.ensureSSLPayload(IOBuffer.java:780)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.readInternal(IOBuffer.java:836)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.read(IOBuffer.java:827)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.readInternal(IOBuffer.java:1009)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.read(IOBuffer.java:997)
at sun.security.ssl.InputRecord.readFully(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1767)
... 11 more
check the port is open or not using on cmd or terminal
telnet 192.168.100.190 1433
and check the database name and credentials
and firewall there is some thing in firewall i think
and take a look here may help you
I'm trying to connect a Java application to a Redshift database. When I run DriverManager.getConnection(), it sits for a long time (minutes) and finally throws an exception:
Exception in thread "main" java.sql.SQLException:
[Amazon](600001) The server closed the connection.
at com.amazon.support.channels.TLSSocketChannel.readBytes(Unknown Source)
at com.amazon.support.channels.TLSSocketChannel.doHandshake(Unknown Source)
at com.amazon.support.channels.TLSSocketChannel.<init>(Unknown Source)
at com.amazon.redshift.client.PGClient.checkSSL(Unknown Source)
at com.amazon.redshift.client.PGClient.<init>(Unknown Source)
at com.amazon.redshift.core.PGJDBCConnection.connect(Unknown Source)
at com.amazon.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
at com.amazon.jdbc.common.AbstractDriver.connect(Unknown Source)
at com.amazon.redshift.jdbc.Driver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
I can connect using the same connection string and credentials from SQL Workbench on the same machine. Also, if I supply bad credentials to the connection, it gives an authentication error. So I don't believe this is an Amazon security issue, which seems to be the most common reason for an inability to connect.
Other ideas?
Update: The mystery deepens. Other members of the team are able to check out the code and run it successfully. We have the driver in our team's shared maven repository.
Well... not sure what the problem was. But I did an Eclipse update and it went away.
I am testing one simple program that is connecting to DB and fetch my_test table details.
I am getting exception as java.sql.SQLException: Unable to load authentication plugin.
stack trace
java.sql.SQLException: Unable to load authentication plugin ''.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:923)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1715)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2412)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2445)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2230)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at TestRoot.main(TestRoot.java:19)
I am using Driver as MySQL.
My Database is mariadb-5.5.30.
Connection con=null;
Statement st=null;
ResultSet rs=null;
String firstName="";
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/my_test","root","");
st=con.createStatement() ;
rs=st.executeQuery("SELECT * FROM test") ;
while(rs.next())
{
firstName=rs.getString(2);
System.out.println(firstName);
}
}
catch(Exception err)
{
System.out.println(err.toString());
}
I knew Connection, ResultSet are not closed, but that cannot be the cause of issue I think.
You may want to take a look here : https://mariadb.atlassian.net/browse/MDEV-3935
the issue occurs when the password set on the mysql.user table uses an
older format - of the form 7f84554057dd964b (which I believe is
'badpwd') rather than something like
*AAB3E285149C0135D51A520E1940DD3263DC008C which is the newer form.
Resetting the password for the user record(s) as noted in MDEV-545
does solve the issue as it upgrades the password format in the tables.
From MariaDB documentation : https://mariadb.com/kb/en/pam-authentication-plugin/
Note: Windows does not use PAM, so the PAM authentication plugin does not work on Windows. However, one can use the Windows client to connect to a MariaDB server — on Linux or Solaris, for example — which does use the PAM authentication plugin. See this example.
From what I understand you should install it on linux (read the doc from the previous link)
I had the same problem and managed to fix it by changing the jdbc driver. I used MariaDB jdbc driver:
(from the Spring configuration file)
Hope this will be helpful.
Im getting
I/O Error: DB server closed connection.
while connecting to MS SQL server 2008 from java code .
SQL server is in mixed mode and its in local machine.My connection string is
jTDS
jdbc:jtds:sqlserver://machineName:1433;databaseName=DB;integratedSecurity=true
stack trace is
java.sql.SQLException: I/O Error: DB server closed connection.
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2311)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:610)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.(ConnectionJDBC2.java:345)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.app.hibernate.test.(test.java:22)
at com.app.hibernate.test.main(test.java:53)
Caused by: java.io.IOException: DB server closed connection.
at net.sourceforge.jtds.jdbc.SharedSocket.readPacket(SharedSocket.java:848)
at net.sourceforge.jtds.jdbc.SharedSocket.getNetPacket(SharedSocket.java:727)
at net.sourceforge.jtds.jdbc.ResponseStream.getPacket(ResponseStream.java:466)
at net.sourceforge.jtds.jdbc.ResponseStream.read(ResponseStream.java:103)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2206)
... 8 more
Exception in thread "main" java.lang.NullPointerException
at com.app.hibernate.test.db(test.java:36)
at com.app.hibernate.test.main(test.java:54)
JDBC Driver
String url ="jdbc:sqlserver://machine:1433;instance=SQLEXPRESS;databaseName=db";
stacktrace
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'username'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:156)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:240)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:78)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2636)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2046)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2034)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4003)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1550)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1207)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.loginWithoutFailover(SQLServerConnection.java:1054)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:758)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.app.hibernate.test.(test.java:22)
at com.app.hibernate.test.main(test.java:53)
Exception in thread "main" java.lang.NullPointerException
at com.app.hibernate.test.db(test.java:36)
at com.app.hibernate.test.main(test.java:54)
Your Connection String and authentication have errors. if it is mix mode don't use SQL authentication
Try this
PC Name : janaka-pc SQL User Name : sa SQL Password
: 1234 Database : Janak_DB
Code for sql Conncetion in JDBC
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://janaka-PC;user=sa;password=1234;database=Janak_DB");
You have problems in your connection strings
For jTDS:
jdbc:jtds:sqlserver://machineName:1433;databaseName=DB;useNTLMv2=true;domain=workgroup
You may read http://jtds.sourceforge.net/faq.html#windowsAuth for the required Single-Sign-On library for NTLM to work.
"integratedSecurity=true" that you supplied for jdts is valid when using the JDBC driver
jdbc:sqlserver://machine:1433;instance=SQLEXPRESS;databaseName=db;integratedSecurity=true
You have an authentication error in on the MS SQL side.
If you're not in control of how to adquire the connection (ie, you're using a Datasource or a Connection Pool), the connection URL must contain the login and password to be used, like:
jdbc:sqlserver://machine:1433;instance=SQLEXPRESS;databaseName=db;user=USERNAME;password=PASSWORD";
If the application is running on a Windows machine and you want to use the credentials of the logged user, then you can specify the domain parameter with or without useNTLMv2.
Finally, if you are on a windows machine but you want to authenticate the user against a domain, then you must supply the username, password and domain parameters. You can read all about it in the jtds FAQ, specially the URL Format section.
I am trying to connect to a remote mysql database but I get the following error
java.sql.SQLException: Cannot connect to MySQL server on biomancy.com:3306. Is
here a MySQL server running on the machine/port you are trying to connect to? (
ava.lang.NumberFormatException)
at org.gjt.mm.mysql.Connection.connectionInit(Unknown Source)
at org.gjt.mm.mysql.jdbc2.Connection.connectionInit(Unknown Source)
at org.gjt.mm.mysql.Driver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at cliche.database.ClicheDBManager.<init>(ClicheDBManager.java:33)
at cliche.server.ClicheExtension.init(ClicheExtension.java:43)
The code in the init function trigger this chain is simply:
myConnection = DriverManager.getConnection(connectionString, user, pass);
I can connect to the database using the commandline mysql from this same computer just fine using the same credentials, and it let me know I had the password wrong when I tried with the wrong password.
Thank you in advance for your help, I hope I gave enough information here.
My best guess is the driver is not the right version. Double check that you have a current version of the driver or try a different driver. Also double check that mysql running on the default port (3306).