Connecting to local instance of PostgreSql with JDBC - java

I have a running local instance of PostgreSql on a linux machine. When I use psql command from the shell I success to log in without any problem. I need to connect to the PostgreSql via the JDBC, but I don't know what exactly should I pass as url parameter to DriverManager.getConnection().
It should start with jdbc:postgresql: but what's going next?
I was told by the system group that a database with was created like user name. e.g. if my user is jutky a db named jutky was created, but when I try to open a connection to jdbc:postgresql:jutky I get an error
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "jutky"
:(
Additional info
When I login via the psql I'm not prompted for the password, so when I try to login via JDBC I pass an empty string as a password - is it correct, or should I pass null or something?
When I type psql --help in the shell I see among the rest this line:
Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "/var/run/postgresql")
So I understand that I connect to PostgreSql via a socket directory, does that matters something to the URL string in the JDBC?
EDIT
First thanks for the answers.
Second: its not first time I'm using JDBC and in particular not the first time I'm connecting to the PostgreSql from JDBC, so I know the general rules and I have read the documentations. However in the described case I'm not sure how exactly should I construct the connection string if the instance is running via the socket directory and what password should I provide. Because when I login via the psql I'm not prompted for password at all.
Thanks in advance.

In addition to other answers note that by default Postgres is configured to accept connections via Unix sockets with authentication based on your operating system account, that's why psql works fine and doesn't require the password.
JDBC connections are made over TCP/IP with password authentication, so you need to modify pg_hba.conf accordingly. For example, this line allows TCP/IP connections from the same machine to all databases for all users with password authentication:
host all all 127.0.0.1/32 md5
After adding this line jdbc:postgresql:databasename should work.
EDIT: You can't create a JDBC connection over Unix socket since PostgreSQL JDBC driver can only work over TCP/IP. The password you use when creating JDBC connection is the password assigned to your user. If you don't have it, you can assign it, for example, using ALTER USER command. See 19.3. Authentication methods.
See also:
19.1. The pg_hba.conf file

It's all explained in official documentation.
This is the relevant part:
String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
Connection conn = DriverManager.getConnection(url);

Related

H2 Client couldn't connect to the server

I am trying to connect to H2 Server started on the same machine using java. I started the H2 server in mixed mode. While connecting to the server I am getting Error.
The code to start the server is:
Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpSSL").start();
The code to connect to the server is:
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:tcp://127.0.0.1/~/Data/test", "", "");
The Error is:
Connection is broken: "unexpected status 352518912" [90067-197]
Anybody please help me with this. I am stuck at this for two days.
You need to use ssl protocol instead of tcp in the URL, because you use an encrypted socked on the server.
"jdbc:h2:ssl://127.0.0.1/~/Data/test"
Please also note that database cannot be created remotely by default in recent versions of H2 due to security reasons. You need to create the database on the server side with a local url such as "jdbc:h2:~/Data/test", it's enough to open and close a connection to it.
Also I hope that empty password is only for that example code in the question. If you have a database that has an user with ADMIN privileges (username and password from the first connection that creates the database are used to create such user) and an empty or weak password (or if you enable the remote database creation), anyone, who can connect to that port, will get full access to your server process and this process most likely already has the same access to your system as you, so you effectively create a remote security hole with -tcpAllowOthers and such passwords.

How to create JDBC data source in Oracle WebLogic server properly?

I'm trying to create a JDBC data source in Oracle WebLogic server and getting some error. I can log in the web console http://localhost:7001/console using user name + password and I followed the Youtube video / tutorial page - Configuring a JDBC data source as same.
I have a wireless connection and I get the Host name (# 12 in the tutorial ) by typing
ipconfig getifaddr en0
in the Mac OS terminal. It returns 10.131.173.138 ( the same format, I changed three random digits ) and I put it inside the Host name and also filled up all other information's. However, after that when I'm trying to test the set up by clicking Test Configuration, it returns me the following errors that I provided below -
Connection test failed.
Message icon - Error IO Error: The Network Adapter could not establish the connectionoracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:800)oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:793)oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:614)weblogic.jdbc.common.internal.DataSourceUtil.testConnection0(DataSourceUtil.java:340)weblogic.jdbc.common.internal.DataSourceUtil.access$000(DataSourceUtil.java:22)weblogic.jdbc.common.internal.DataSourceUtil$1.run(DataSourceUtil.java:254)java.security.AccessController.doPrivileged(Native Method)weblogic.jdbc.common.internal.DataSourceUtil.testConnection(DataSourceUtil.java:251)com.bea.console.utils.jdbc.JDBCUtils.testConnection(JDBCUtils.java:751)com.bea.console.actions.jdbc.datasources.createjdbcdatasource.CreateJDBCDataSource.testConnectionConfiguration(CreateJDBCDataSource.java:479)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:606)org.apache.beehive.netui.pageflow.FlowController.invokeActionMethod(FlowController.java:870)org.apache.beehive.netui.pageflow.FlowController.getActionMethodForward(FlowController.java:809)org.apache.beehive.netui.pageflow.FlowController.internalExecute(FlowController.java:478)org.apache.beehive.netui.pageflow.PageFlowController.internalExecute(PageFlowController.java:306)org.apache.beehive.netui.pageflow.FlowController.execute(FlowController.java:336)...
I think it mainly says The Network Adapter could not establish the connection
However, I don't have much knowledge what to do to establish the connection properly. Thanks.
You need a real database with correct values in the jdbc URL:
i.e.
For example, if the database to which you want to connect resides on host prodHost, at port 1521, and system identifier (SID) ORCL, and you want to connect with user name scott and password tiger, then use either of the two following connection strings:
Using host:port:sid syntax:
String connString="jdbc:oracle:thin:#prodHost:1521:ORCL";

Can't connect to SQL Server using jTDS

I'm trying to connect to SQL Server 2008 R2 via Java, and I'm unable to do so using jTDS 1.2.8. The odd thing is that it works fine using the Microsoft JDBC driver. Is there some server-side setting that needs to be turned on to enable jTDS to access it? Or am I just missing something in the URL?
I'm not using Windows integrated authentication to specify credentials, nor am I attempting to connect using SSL encryption (those are issues I found that can generate the exception I'm seeing.)
If I use the following with the Microsoft driver, it works as expected, I can access the database with no problems:
Connection connection = DriverManager.getConnection("jdbc:sqlserver://PHSSQL792\\PHSSQL792:1433", user, password);
(user and password are variables declared earlier, so I can be sure I use the same values when connecting with either driver.)
However, if I use the following with the jTDS driver:
Connection connection = DriverManager.getConnection("jdbc:jtds:sqlserver://PHSSQL792:1433;instance=PHSSQL792", user, password);
I get the following error:
java.sql.SQLException: I/O Error: DB server closed connection.
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2387)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:614)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:356)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:185)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at database.db_access.SqlServerDatabaseTestApp.main(SqlServerDatabaseTestApp.java:28)
Caused by: java.io.IOException: DB server closed connection.
at net.sourceforge.jtds.jdbc.SharedSocket.readPacket(SharedSocket.java:853)
at net.sourceforge.jtds.jdbc.SharedSocket.getNetPacket(SharedSocket.java:732)
at net.sourceforge.jtds.jdbc.ResponseStream.getPacket(ResponseStream.java:477)
at net.sourceforge.jtds.jdbc.ResponseStream.read(ResponseStream.java:114)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2281)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:614)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:356)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:185)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at database.db_access.SqlServerDatabaseTestApp.main(SqlServerDatabaseTestApp.java:28)
I've tried connecting with and without the database name, and/or with/without the instance name, and got the same results. Any suggestions?
Edit:
Other jTDS connection URLs I've tried (which all gave me the same error as above):
"jdbc:jtds:sqlserver://PHSSQL792:1433"
"jdbc:jtds:sqlserver://PHSSQL792:1433/pacsdb"
"jdbc:jtds:sqlserver://PHSSQL792:1433/pacsdb;instance=PHSSQL792"
The corresponding Microsoft URLS (which all worked):
"jdbc:sqlserver://PHSSQL792:1433"
"jdbc:sqlserver://PHSSQL792:1433;databasename=pacsdb"
"jdbc:sqlserver://PHSSQL792\\PHSSQL792:1433;databasename=pacsdb"
Also, I can successfully connect to a different SQL Server 2008 R2 database (on a different server) using the jTDS driver, so it's not the jar.
In case anyone ever runs into this, I came back to this much later and finally figured out the problem. The SQL Server instance in question was configured to require SSL connections! I just added ssl=request to the URL to make it work.
I think the reason the Microsoft driver works without explicitly setting SSL encryption is that it ALWAYS initially connects with SSL to encrypt username/password for login. The encrypt property only controls whether data after login is encrypted.
Here's the format we are using, which looks very close to your:
jdbc:jtds:sqlserver://localhost:1433/Dev_DB;tds=8.0;lastupdatecount=true
It's strange, yours connection strings looks correct. Try to set user and password directly:
"jdbc:jtds:sqlserver://PHSSQL792:1433/pacsdb;instance=PHSSQL792;user=sa;password=pass"
String driver="net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//First way
String connString="jdbc:jtds:sqlserver://192.168.1.123:1433/database_name;encrypt=false;user=sa;password=mypass;";
String username="sa";
String password="mypass";
Connection con=DriverManager.getConnection(connString,username,password);
//Second way
String connString="jdbc:jtds:sqlserver://127.0.0.1:1433/database_name;encrypt=false;user=sa;password=mypass;integratedSecurity=true;instance=SQLEXPRESS;";
String username="sa";
String password="mypass";
Connection con=DriverManager.getConnection(connString,username,password);

HSQLDB server mode username/password

If I start the HSQLDB in server mode using my Java code, the server starts without any problem. However, when I try to connect to the same either through the Java code or through the HSQLDB DatabaseManagerSwing; I am unable to connect.
I started the server with user=conn1 and password=conn1 in memory-only mode. But when connecting to the server it gave me following exception:
java.sql.SQLInvalidAuthorizationSpecException: invalid authorization specification - not found: conn1
I can only connect by giving user=SA and blank password. I am using HSQLDB 2.2.5 and JRE1.7 on Windows7 machine.
Can someone tell me where am I doing wrong?
If you try these server properties with recent versions of HyperSQL, you will probably get an error message as your server properties are not correct. The properties "server.username" and "server.password" are not valid. And the dbname.0 property must be in lowercase.
If you want to create a server database with a user name other than SA, you can append the user and password to the database path:
server.database.0 = file:E:/DB/myDB;user=testuser;password=testpw
server.dbname.0 = mydb
After the server is shutdown, there is no need to include the user and password. The credentials are used only to create the database. After that, the credentials are checked when a connection is made to the server.
2020 update with additional information due to recent questions in comments:
The user name and password specified for database.0 are taken into account only when a new database is created by starting the server. If the database files exist before starting the server, user name and password are unnecessary and are simply ignored.
Other settings for a new database, such as hsqldb.tx=mvcc, can be appended to the database.0 string.
You must have properties for database.0 for your server. You can add properties for database.1 if your server is serving two different databases.
The file path specified for database.0 is hidden from the users that connect to the server. Only the dbname.0 value is used for access, for example:
DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/mydb;uer=testuser;password=testpw")
In the getConnection call, it is better to state the user and password separately to keep the code clear:DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/mydb", "testuser", "testpw")
See the Guide http://hsqldb.org/doc/2.0/guide/dbproperties-chapt.html for all the details.
Appears the problem you were running into (at least initially) is that, for HSQL in memory databases, if it's the "first" in memory database (i.e. process just started), the username "has to be" sa (username "sa" is not case sensitive, or it can be empty username, which implies the "default" which is also sa). You can use a blank password, or specify a password. Based on some trial and error, if you want to reconnect to the same (in memory) DB later, you'll have to re-use the same password (blank or otherwise). If you want to use a user other than SA you'd probably have to first connect to your database using SA and execute some "create user" type commands to create new users. Then reconnect using that user (assuming your DB is all in memory).
You can use multiple different in-memory databases (if that's what you're trying to accomplish by specifying a different user) like this:
// change the MySpecialTestDb String for multiple different in memory databases
// or reuse the same value
// to reconnect to a previously created in memory database [i.e. within the same process previously].
String DB_CONNECTION_STR = "jdbc:hsqldb:mem:MySpecialTestDb";
String DB_USERNAME_STR = "sa";
String DB_USERNAME_PASSWORD = "";
DriverManager.getConnection(DB_CONNECTION_STR, DB_USERNAME_STR, DB_USERNAME_PASSWORD);
Each new database you create follows the same system (it must be initial user SA and "adopts" whatever first password you give).
ref: http://www.hsqldb.org/doc/1.8/guide/guide.html#advanced-chapter
Or if you want to just "reset" an in memory database, like between each unit test, see here.
Note that documentation also says "...This feature [default user SA] has a side effect that can confuse new users. If a mistake is made in specifying the path for connecting to an existing database, a connection is nevertheless established to a new database. For troubleshooting purposes, you can specify a connection property ifexists=true ..."
Point no 1) Whenever you create a DB, you have to specify the username and password. You can keep it both blank; But same username and password has to be used while connecting to server.
If you observe script file of your DB, you can see commands like :-
CREATE USER "usr" PASSWORD DIGEST '9003d1df22eb4d3820015070385194c8'
ALTER USER "usr" SET LOCAL TRUE
GRANT DBA TO "usr"
I had created DB with user name "usr" so it appeared in script file in those commands. Now while starting server I do not need to specify user name or password. It will IGNORE this information.
While connecting server you have to give exactly same username and password, you gave while creating DB.
Point no 2)
Make sure that there is no space in path of your DB files. If there is space then enclose the whole path in double quotes.
I struggled a lot to find out this silly mistake of mine.
Now if I start the server wil below command it starts correctly
1) Go to lib of HSQL
cd C:\Users\owner\Documents\Java Project\hsqldb-2.2.9\hsqldb\lib
Then give command
java -cp hsqldb.jar org.hsqldb.Server -database.0 file:"C:\Users\owner\Documents\Java Project\hsqldb-2.2.9\TmpDBLocation\myKauDB" -dbname.0 xdb
2) In other command prompt went to lib location
cd C:\Users\owner\Documents\Java Project\hsqldb-2.2.9\hsqldb\lib
Then connected the Swing UI of HSQL DB by giving command in other command prompt window
java -cp hsqldb.jar org.hsqldb.util.DatabaseManagerSwing --driver org.hsqldb.jdbcDriver --URL jdbc:hsqldb:hsql://localhost/xdb --user "usr" --password ""
In my brand new 2.3.2 installation, after clicking bin/runServer.bat, I managed to connect (with Squirrel) using:
URL: jdbc:hsqldb:hsql://localhost:9001
User: SA
Password: <blank>

Is it possible to create a jdbc connection without a password (using postgresql 'trust')?

I am using jdbc to connect to a postgresql database in a java application (actually the app is written in Groovy). I have postgresql set up to use the 'trust' authentication method. Is it possible to open a jdbc connection without specifying a password? When I try to use the normal constructor with a blank password, it fails with
Exception in thread "Thread-2" org.postgresql.util.PSQLException: FATAL: password authentication failed for user "myuser"
Even though, from the command line, this works fine
psql -U myuser mydatabase
Welcome to psql 8.3.5, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
Yes, you can.
Note that Postres JDBC driver always uses IP sockets (host in pg_hba.conf), even if database is on the local machine, then psql can use local sockets (local in pg_hba.conf). So, if psql works with trust authentication and JDBC doesn't, you probably should configure trust authentication for IP sockets, see documentation.
Already answered but:
When you connect using the psql client program, and don't specify a host (-h), the default is to use a local socket (at least in Linux). In JDBC, instead, you will use a TCP/IP socket. Then, to check your connection problem you should invoke psql with the same settings you are using in JDBC, host included.
For example
psql -U myuser -h 127.0.0.1 mydatabase # uses TCP/IP
Which is not the same as
psql -U myuser mydatabase # uses local socket (non TCP/IP)
GlassFish at least including version 3.1 has an issue with specifying empty JDBC passwords.

Categories

Resources