I use Ubuntu & Net-beans. I make a java desktop database application from Netbeans wizard. I use MySQL database which I can open & run query from its Services → Databases. When I run it I got the Exception below. When I clean & Build the Project run jar file, same Exception. I have installed Windows in the same machine dual boot way, and also have the same MySQL database & Java. When I run the jar file I make using Ubuntu Netbeans, it perfectly run in Windows and show the database data. I did the other way also, I make the same java application in Windows Netbeans using the same database and it run perfectly both withing the Netbeans and jar file. But when I try to run it in Ubuntu, both in Netbeans & jar file show the below Exception.
[TopLink Info]: 2012.01.29 11:16:58.898--ServerSession(285416048)--TopLink, version: Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))
Jan 29, 2012 11:16:59 AM org.jdesktop.application.Application$1 run
SEVERE: Application class customerrecordsu.CustomerRecordsUApp failed to launch
Local Exception Stack:
Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Error Code: 0
at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:305)
... lot of more
Caused by: java.net.SocketException: Can't connect to SOCKS proxy:Connection refused
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:427)
... lot of more
Below is part of 'my.cnf' file removing comments.
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
user = mysql
socket = /var/run/mysqld/mysqld.sock
port = 3306
skip-external-locking
bind-address = 127.0.0.1
below is part of persistance.xml file
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/MyBusinessRecords"/>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.password" value="password"/>
Netbeans wizard use JPA, & Top Link. I make a program without wizard by pure Java, it worked perfectly in Ubuntu as expected and show the database data. That program is below. Both above and below use same Java MySQL connector.jar.
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
int id = 0;
String name = null;
try {
String url = "jdbc:mysql://localhost:3306/MyBusinessRecords";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, "root", "5843");
if (con != null) {
System.out.println("A database connection has been establised!");
st = con.createStatement();
rs = st.executeQuery("select * from COUNTRIES");
while(rs.next()){
id = rs.getInt(1);
name = rs.getString(2);
System.out.println("id = " + id + " Name = " + name);
}
}
} catch (Exception e) {
System.out.println("Problem" + e.toString());
} finally {
if (con != null) {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println(e.toString());
}
con = null;
}
}
}
This is my system
java version "1.7.0_01"
Java HotSpot(TM) 64-Bit Server VM (build 21.1-b02, mixed mode)
Ubuntu 11.10. OS type 64 bit
MySQL Version- MySQL 5.1.58-1ubuntu1
MySQL Client Version 5.1.58
Socket: /var/run/mysqld/mysqld.sock
I read the Q & A more then 15 in this site with same question, but that now one helped me. Please help me.
String url = "jdbc:mysql://localhost:3306/MyBusinessRecords";
Caused by: java.net.SocketException: Can't connect to SOCKS proxy:
a non-existant SOCKS proxy
bind-address = 127.0.0.1
You can try bind-address = 0.0.0.0 or jdbc:mysql://127.0.0.1:3306/MyBusinessRecords"
Try Java 1.6. I had a similar issue and changed back to Java 1.6 (I had upgraded to 1_7) and the issue went away. Probably need a different toplink or OracleDriver release for 1_7.
Related
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.
im trying to create a connection to the MSSQL08 database on my computer :
this is my simple piece of code :
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException {
String userName ="username";
String password ="password";
String url ="jdbc:microsoft:sqlserver://localhost; databaseName=Lando";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection conn = DriverManager.getConnection(url, userName, password);
} catch (SQLException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
i get this Error :
SEVERE: null java.sql.SQLException: No suitable driver found for
jdbc:microsoft:sqlserver://localhost; databaseName=Lando at
java.sql.DriverManager.getConnection(DriverManager.java:596) at
java.sql.DriverManager.getConnection(DriverManager.java:215) at
javaapplication2.JavaApplication2.main(JavaApplication2.java:34)
when i change the URL to this : "jdbc:sqlserver://localhost; databaseName=Lando"
then i get this Error :
SEVERE: Java Runtime Environment (JRE) version 1.7 is not supported by
this driver. Use the sqljdbc4.jar class library, which provides
support for JDBC 4.0. Exception in thread "main"
java.lang.UnsupportedOperationException: Java Runtime Environment
(JRE) version 1.7 is not supported by this driver. Use the
sqljdbc4.jar class library, which provides support for JDBC 4.0. at
com.microsoft.sqlserver.jdbc.SQLServerConnection.(SQLServerConnection.java:304)
at
com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1011)
at java.sql.DriverManager.getConnection(DriverManager.java:571) at
java.sql.DriverManager.getConnection(DriverManager.java:215) at
javaapplication2.JavaApplication2.main(JavaApplication2.java:34)
I added the sqldjbc4.jar file to the project libraries in neatbeans, i also set the CLASSPATH in enviroment variables to the directory of the Microsoft Driver.
what could be the problem ?
This question already has answers here:
SqlServer: Login failed for user
(14 answers)
Closed 4 years ago.
I am simply trying to test my connection with SQL Server 2008 as follows:
public class ForJDBC {
public static void main(String[] args) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlserver://XX.XX.X.XXX:1433;databaseName=MyDB;user=sa;password=mypassword");
if(conn != null){
System.out.println("Connection is Successfull");
}
}
catch(SQLException ex){
ex.printStackTrace();
}
}
}
But I keep on getting the following exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'sa'. ClientConnectionId:96f7d048-9734-4fd8-8216-21231d89b2e6
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2908)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at forjdbc.ForJDBC.main(ForJDBC.java:35)
When I connect to MySQL 5.5, it works fine.
Troubleshooting Steps I have followed:
1) Tried Logging with the "sa" user name and password within the SQL Server Management Console
using SQL Server Management studio
2) I have sqljdbc4.jar in my Source Package folder of Netbeans 7.4
3) Updated to Java 8
Please let me know what am I doing wrong and let me know if I can answer any questions.
Connection String Problem...
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager
.getConnection("jdbc:sqlserver://localhost:1433;\SQLEXPRESS;databaseName=Tema6","sa","123456")
I think you missed loading the Driver class and registering it.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
If still it is not working then please ensure your SQLServer services is running
Click SQL --> click right mouse --> propretise --> Securiti -->tick SQL server and windows Authentication mode
90% success!
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>