I am new to docker, attempting to connect oracle database running in local from an application running inside docker.
Getting below error:
IO Error: The Network Adapter could not establish the connection.
I browsed that we can pull oracle image and run in the docker container but I want to connect locally running database.
Can someone please guide me how to connect oracle database running in local windows machine from application inside docker container.
Code to get SessionFactory instance:
private SessionFactory getSessionFactory() {
SessionFactory sessionFactory = null;
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's
// properties
System.out.println("SessionFactory getting called");
Properties settings = new Properties();
settings.put(Environment.DRIVER, "oracle.jdbc.driver.OracleDriver");
settings.put(Environment.URL, "jdbc:oracle:thin:#localhost:1521:xxxxx");
settings.put(Environment.USER, "xxxxx");
settings.put(Environment.PASS, "xxxx");
settings.put(Environment.DIALECT, "org.hibernate.dialect.Oracle12cDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.C3P0_MIN_SIZE, 10);
settings.put(Environment.C3P0_MAX_SIZE, 100);
settings.put(Environment.C3P0_TIMEOUT, 300);
configuration.setProperties(settings);
configuration.addAnnotatedClass(SecretQuestionsEnity.class).addAnnotatedClass(CustomerEntity.class)
.addAnnotatedClass(AddressEntity.class).addAnnotatedClass(SecretAnswersEntity.class)
.addAnnotatedClass(BranchEntity.class).addAnnotatedClass(AccountEntity.class)
.addAnnotatedClass(CurrentACEntity.class).addAnnotatedClass(SavingsACEntity.class)
.addAnnotatedClass(TransactionEntity.class).addAnnotatedClass(PayeeEntity.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
Error :
2020-07-24 16:32:09 WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 17002, SQLState: 08006
2020-07-24 16:32:10 ERROR o.h.e.jdbc.spi.SqlExceptionHelper - IO Error: The Network Adapter could not establish the connection
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
If you are running an application inside docker container then the localhost refers to container not your local windows machine
settings.put(Environment.URL, "jdbc:oracle:thin:#localhost:1521:xxxxx");
Either you can give your windows machine IP address instead of localhost in the URL string or you can read it from environment variable by passing it in docker run command.
Related
I'm trying to connect to a mail server using IMAP protocol and proxies with the JavaxMail library. Yet they seem not to work.
Properties properties = new Properties();
List<Message> messages = new ArrayList<>();
Host host = Host.getHostByMail(mail);
properties.put("proxySet", "true");
properties.put("mail.imap.proxy.host", "proxy host");
properties.put("mail.imap.proxy.port", "proxy port");
properties.put("mail.imap.proxy.user", "proxy user");
properties.put("mail.imap.proxy.password", "proxy passwd");
properties.put("mail.imap.host", host.toString());
properties.put("mail.imap.port", "143");
properties.put("mail.imap.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imap");
store.connect(host.toString(), mail, passwd);
Folder readOnly = store.getFolder("INBOX");
readOnly.open(Folder.READ_ONLY);
FlagTerm unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
When I try to use this code it gives me this error:
Exception in thread "Timer-2" com.sun.mail.util.MailConnectException: Couldn't connect to
host, port: imap.tiscali.it, 143; timeout -1; Using web proxy host, port: proxy_host, proxy_port; nested exception is:
java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at mail.MailHandler.readMail(MailHandler.java:97)
at mail.MailHandler.readAllMail(MailHandler.java:143)
at mail.MailSender.onCall(MailSender.java:27)
at commands.Temp$1.run(Temp.java:21)
at java.base/java.util.TimerThread.mainLoop(Timer.java:566)
at java.base/java.util.TimerThread.run(Timer.java:516)
Caused by: java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.util.SocketFetcher.proxyConnect(SocketFetcher.java:877)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 8 more
This happens when I use HTTP/HTTPS proxies, but when I use SOCKS proxies it gives
Connection dropped by server?
I'm doing a Proof-of-Concept (PoC) Java reporting project in which I'm connecting to a SSL-enabled Oracle database from my workstation, using JDBC Thin driver. As the database is SSL-enabled, I added all the required certificates into a Oracle Wallet and provided its location in the Java code. The certs were also added cacert of the JRE. Java code excerpt -
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("ERROR: Oracle JDBC Driver not found");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
String oracleURL = "jdbc:oracle:thin:#(DESCRIPTION(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCPS)(HOST=<hostname>)(PORT=2484)))(CONNECT_DATA=(SERVICE_NAME=<service>)))";
// Provide user ID, password for schema
Properties props = new Properties();
props.setProperty("user", "<user id>");
props.setProperty("password", "<password>");
// Setting properties for SSL
props.setProperty("oracle.net.ssl_cipher_suites", "(ssl_rsa_export_with_rc4_40_md5, ssl_rsa_export_with_des40_cbc_sha, SSL_DH_anon_WITH_3DES_EDE_CBC_SHA, SSL_DH_anon_WITH_RC4_128_MD5,SSL_DH_anon_WITH_DES_CBC_SHA)");
props.setProperty("oracle.net.ssl_client_authentication", "false");
props.setProperty("oracle.net.ssl_version", "3.0");
props.setProperty("oracle.net.encryption_client", "REJECTED");
props.setProperty("oracle.net.crypto_checksum_client", "REJECTED");
props.setProperty("javax.net.ssl.keyStore", "C:\\APP\\ORACLE\\product\\11.2.0\\client_1\\ewallet.p12");
props.setProperty("javax.net.ssl.keyStoreType","PKCS12");
props.setProperty("javax.net.ssl.keyStorePassword","Password1");
try {
connection = DriverManager.getConnection(oracleURL, props);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
System.out.println("Error code: " + e.getErrorCode());
System.out.println("SQL State: " + e.getSQLState());
e.printStackTrace();
return;
}
I'm able to compile the program and also run it using the following -
java -cp z:\jdk1.7.0_13\bin\ojdbc14.jar;z:\jdk1.7.0_13\bin OracleConnCheck
where:
z:\jdk1.7.0_13\bin\ojdbc14.jar - location of ojdbc14.jar
z:\jdk1.7.0_13\bin - Java classpath
OracleConnCheck - Java class
But I always encounter IO error accompanied with NL exception or SO exception. I checked out the Oracle and few articles related to the same exception in here but none addressed my exact problem. Could someone help? Thanks!
Edit: Adding the stacktrace -
Oracle JDBC Driver Registered!
Connection Failed! Check output console
Error code: 17002
SQL State: null
java.sql.SQLException: Io exception: NL Exception was generated
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:147)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:257)
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:579)
at java.sql.DriverManager.getConnection(DriverManager.java:190)
at OracleConnCheck.establishConnection(OracleConnCheck.java:51)
at OracleConnCheck.main(OracleConnCheck.java:72)
------- The End -------
Make sure you use the latest 12.1.0.2 JDBC drivers. You can download from OTN. Also, you need to include osdt_core.jar and osdt_cert.jar.
Refer to SSL with Oracle JDBC whitepaper for more details.
"NL Exception was generated" indicates that there is a format error in the connection string. In your case you are missing = after DESCRIPTION.
I'm trying to connect to mongodb server which is running on remote Linux machine using java code,
public static void main(String[] args) {
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("src/main/resources/mongodb.properties"));
String server = prop.getProperty("server");
String port = prop.getProperty("port");
int portnum = Integer.parseInt(port);
/**** Connect to MongoDB ****/
MongoClient mongo = new MongoClient(server,portnum);
System.out.println("Connected to database");
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("test");
/**** Get collection / table from 'details' ****/
// if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("details");
/**** Insert ****/
// create a document to store key and value
BasicDBObject document = new BasicDBObject();
document.put("name", "test");
document.put("age", 24);
table.insert(document);
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "test");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
It is working fine with my local mongo. But facing an issue while trying to connect with linux server.
Here is the error message,
Jan 18, 2016 12:23:02 AM com.mongodb.DBTCPConnector initDirectConnection
WARNING: Exception executing isMaster command on server:port
java.io.IOException: couldn't connect to [server port] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:214)
at com.mongodb.DBPort.go(DBPort.java:107)
at com.mongodb.DBPort.go(DBPort.java:88)
at com.mongodb.DBPort.findOne(DBPort.java:143)
at com.mongodb.DBPort.runCommand(DBPort.java:148)
at com.mongodb.DBTCPConnector.initDirectConnection(DBTCPConnector.java:548)
at com.mongodb.Mongo.getMaxBsonObjectSize(Mongo.java:620)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:254)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
at com.mongodb.DBCollection.insert(DBCollection.java:75)
at com.mongodb.DBCollection.insert(DBCollection.java:59)
at com.mongodb.DBCollection.insert(DBCollection.java:104)
at com.filecompare.util.MongoDBConnection.main(MongoDBConnection.java:42)
Jan 18, 2016 12:23:03 AM com.mongodb.DBTCPConnector initDirectConnection
WARNING: Exception executing isMaster command on sever port
java.io.IOException: couldn't connect to [server port] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:214)
at com.mongodb.DBPort.go(DBPort.java:107)
at com.mongodb.DBPort.go(DBPort.java:88)
at com.mongodb.DBPort.findOne(DBPort.java:143)
at com.mongodb.DBPort.runCommand(DBPort.java:148)
at com.mongodb.DBTCPConnector.initDirectConnection(DBTCPConnector.java:548)
at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:527)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:174)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:155)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:270)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
at com.mongodb.DBCollection.insert(DBCollection.java:75)
at com.mongodb.DBCollection.insert(DBCollection.java:59)
at com.mongodb.DBCollection.insert(DBCollection.java:104)
at com.filecompare.util.MongoDBConnection.main(MongoDBConnection.java:42)
Jan 18, 2016 12:23:04 AM com.mongodb.DBPortPool gotError
WARNING: emptying DBPortPool to server:port b/c of error
java.io.IOException: couldn't connect to [server:port] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:214)
at com.mongodb.DBPort.go(DBPort.java:107)
at com.mongodb.DBPort.go(DBPort.java:84)
at com.mongodb.DBPort.say(DBPort.java:79)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:181)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:155)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:270)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
at com.mongodb.DBCollection.insert(DBCollection.java:75)
at com.mongodb.DBCollection.insert(DBCollection.java:59)
at com.mongodb.DBCollection.insert(DBCollection.java:104)
at com.filecompare.util.MongoDBConnection.main(MongoDBConnection.java:42)
Exception in thread "main" com.mongodb.MongoException$Network: can't say something
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:194)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:155)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:270)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
at com.mongodb.DBCollection.insert(DBCollection.java:75)
at com.mongodb.DBCollection.insert(DBCollection.java:59)
at com.mongodb.DBCollection.insert(DBCollection.java:104)
at com.filecompare.util.MongoDBConnection.main(MongoDBConnection.java:42)
Caused by: java.io.IOException: couldn't connect to [server port] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:214)
at com.mongodb.DBPort.go(DBPort.java:107)
at com.mongodb.DBPort.go(DBPort.java:84)
at com.mongodb.DBPort.say(DBPort.java:79)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:181)
... 7 more
Steps that I generally follow to connect with mongo on linux are,
Login to server using Putty(windows) or ssh command(Mac).
type in mongo.
Connected to mongo, run mongo commands to view/ insert data.
But, in above java code I didn't include any login credentials. Do I have to do that. If so, could someone please guide me.
Are you sure you're providing the right values for your server and port property variables in mongodb.properties?
Default port for MongoDB is 27017.
Also, check your mongod.conf on the MongoDB server. This file is found, by default at /etc/mongod.conf and look for the following attribute:
bind_ip = 127.0.0.1
If this is set to 127.0.0.1 or localhost, then you won't be able to access your MongoDB server publicly from outside.
Now to fix this, change value of bind_ip to include your public ip address, so if your public address is 46.12.212.34, bind_ip will look like:
bind_ip = 127.0.0.1, 46.12.212.34
Save and exit the file and restart your MongoDB database. Your Java application should now work.
I'm creating a application scoped mongo client to reuse it in my app. The first time the mongo client is accessed I see the following log entires in my server log indicating three clients are created. The third client is the one that is created in application scope as you can see by the preceding info message.
I can additionally see in the mongodb logs that 2 additional connections are opened and not closed or reused by succeeding calls.
[08.09.14 20:09:57:060 CEST] 000000c9 Mongo I Creating Mongo instance (driver version 2.11.4) with authority MongoAuthority{type=Direct, serverAddresses=[/127.0.0.1:27017], credentials={credentials={}}} and options MongoOptions{description='null', connectionsPerHost=100, threadsAllowedToBlockForConnectionMultiplier=5, maxWaitTime=120000, connectTimeout=10000, socketTimeout=0, socketKeepAlive=false, autoConnectRetry=false, maxAutoConnectRetryTime=0, slaveOk=false, readPreference=primary, dbDecoderFactory=DefaultDBDecoder.DefaultFactory, dbEncoderFactory=DefaultDBEncoder.DefaultFactory, safe=false, w=0, wtimeout=0, fsync=false, j=false, socketFactory=javax.net.DefaultSocketFactory#f6fb9709, cursorFinalizerEnabled=true, writeConcern=WriteConcern { "getlasterror" : 1} / (Continue Inserting on Errors? false), alwaysUseMBeans=false}
[08.09.14 20:09:57:060 CEST] 000001ba Mongo I Creating Mongo instance (driver version 2.11.4) with authority MongoAuthority{type=Direct, serverAddresses=[/127.0.0.1:27017], credentials={credentials={}}} and options MongoOptions{description='null', connectionsPerHost=100, threadsAllowedToBlockForConnectionMultiplier=5, maxWaitTime=120000, connectTimeout=10000, socketTimeout=0, socketKeepAlive=false, autoConnectRetry=false, maxAutoConnectRetryTime=0, slaveOk=false, readPreference=primary, dbDecoderFactory=DefaultDBDecoder.DefaultFactory, dbEncoderFactory=DefaultDBEncoder.DefaultFactory, safe=false, w=0, wtimeout=0, fsync=false, j=false, socketFactory=javax.net.DefaultSocketFactory#f6fb9709, cursorFinalizerEnabled=true, writeConcern=WriteConcern { "getlasterror" : 1} / (Continue Inserting on Errors? false), alwaysUseMBeans=false}
[08.09.14 20:09:57:070 CEST] 000000c9 mongodb I multiple Mongo instances for same host, jmx numbers might be off
[08.09.14 20:09:57:070 CEST] 000001ba mongodb I multiple Mongo instances for same host, jmx numbers might be off
[08.09.14 20:09:57:111 CEST] 000001ba SystemOut O INFO MongoDBConnection initializeClient - Creating mongo client for localhost:27017
[08.09.14 20:09:57:111 CEST] 000001ba Mongo I Creating Mongo instance (driver version 2.11.4) with authority MongoAuthority{type=Direct, serverAddresses=[localhost/127.0.0.1:27017], credentials={credentials={}}} and options MongoOptions{description='null', connectionsPerHost=100, threadsAllowedToBlockForConnectionMultiplier=5, maxWaitTime=120000, connectTimeout=10000, socketTimeout=0, socketKeepAlive=false, autoConnectRetry=false, maxAutoConnectRetryTime=0, slaveOk=false, readPreference=primary, dbDecoderFactory=DefaultDBDecoder.DefaultFactory, dbEncoderFactory=DefaultDBEncoder.DefaultFactory, safe=false, w=0, wtimeout=0, fsync=false, j=false, socketFactory=javax.net.DefaultSocketFactory#f6fb9709, cursorFinalizerEnabled=true, writeConcern=WriteConcern { "getlasterror" : 1} / (Continue Inserting on Errors? false), alwaysUseMBeans=false}
Please also note the different server addresses in the logs: serverAddresses=[localhost/127.0.0.1:27017] and serverAddresses=[/127.0.0.1:27017]. I'm setting localhost as the host name in my code.
Below you find the producer method for the mongo client.
#Produces
#ApplicationScoped
public MongoClient initializeClient() {
log.info(String.format("Creating mongo client for %s:%s", host, port));
MongoClient client = null;
try {
client = new MongoClient(host, port);
}
catch (UnknownHostException e) {
log.error(e);
}
return client;
}
Does someone know what causes these two other instances to be created and how can I prevent that?
I am trying to connect to a Microsoft SQL 2008 server via hibernate.
The following is my hibernate.cfg.xml file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://127.0.0.1:1433;databaseName=myDBName;instanceName=myInstanceName;</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pass</property>
<mapping resource="Obj.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And here is the code I use to try and establish an connection and do a query :
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class SessionsTest {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
/**
* #param args
*/
#SuppressWarnings({ "unchecked"})
public static void main(String[] args) {
sessionFactory = configureSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
List<Obj> result = (List<Obj>) session.createQuery("FROM Obj").list();
for (Obj obj : result ) {
System.out.println(obj.getObjID());
}
session.getTransaction().commit();
session.close();
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration config = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
The stacktrace I get :
2013-04-13 15:02:03,449 [main] WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 08S01
2013-04-13 15:02:03,449 [main] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - The TCP/IP connection to the host 127.0.0.1, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:221)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1425)
at com.test.test.ObjTest.main(ObjTest.java:24)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host 127.0.0.1, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1033)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:204)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
... 5 more
I have tried using a different driver(JTDS).
I have tried changing the URL string in various ways.
I have tried changing my dialect to org.hibernate.dialect.SQLServerDialect.
I also tried using windows authentication at one point by adding ;IntegratedSecurity=true to the end of the url string.
Other than this I have been poking around in the server properties to make sure the the instance I am providing is correct aswell as the port.I have tried : telnet localhost 1433 and can't connect that way,but I can connect using SQL Server Management Studio.
Further I used NetStat -o in cmd and TaskList /FI "PID eq 4072" /FO LIST /V to try and track down the sql server to confirm the port aswell.The weird thing is I couldn't track down sql server this way.It does not turn up in the NetStat list,but if I use the PID of the server directly it does show details about it except the Status is Unknown,Session# is 0 and User Name is N/A.
I use Hibernate 4.2.0 and SQLJDBC4,when I used JTDS it was 1.2.7.
The output of java -version :
java version "1.6.0_30"
Java(TM) SE Runtime Environment (build 1.6.0_30-b12)
Java HotSpot(TM) 64-Bit Server VM (build 20.5-b03, mixed mode)
Please tell me if any other info is needed,first time posting here.
I think your SQL Server instance is not serving at 1433 for TCP connections.
To identify the port:
Go to SQL Server configuration manager.
Choose SQL Server Network Configuration
Go for Protocols for Your Instance
Click on TCP IP (Enable it if not enabled, then clients could connect with TCP/IP)
On the popup which results, Choose IP Addresses Tab
Scroll Down
You'll see TCP Dynamic ports in Section IPAll
Grab that value and that's the port you should be using
Really, really, really check if the TCP/IP protocol is enabled in your SQL Server instance.
Follow these steps (tested for SS2012) to make sure:
Open "Sql Server Configuration Manager" in "Start Menu\Programs\Microsoft SQL Server 2012\Configuration Tools\"
Expand "SQL Server Network Configuration"
Go in "Protocols for <YourInstance>"
Enable TCP/IP
If you have any problem, check this blog post for details, as it contains screenshots and much more info.
Also check if the "SQL Server Browser" windows service is activated and running:
Go to Control Panel -> Administrative Tools -> Services
Open "SQL Server Browser" service and enable it (make it manual or automatic, depends on your needs)
Start it.
That's it.
After I installed a fresh local SQL Server, all I had to do was to enable TCP/IP and start the SQL Server Browser service.
Below a code I use to test the connection to a SQLEXPRESS local instance. Of course, you should change the IP, DatabaseName and user/password as needed.:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JtdsSqlExpressInstanceConnect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "user";
String password = "password";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}
And if you use Maven, add this to your pom.xml:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>