Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to sql server from java with jdbc(windows authentication mode)

I need to connect to Sql Server 2008 from java using jdbc 4.0. I have a very simple code:

 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
 String connectionUrl = "jdbc:sqlserver://localhost;" +
    "integratedSecurity=true;";
 Connection con = DriverManager.getConnection(connectionUrl);

But i have this error:

    Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
...

I follow this answer:https://stackoverflow.com/a/12524566/1554397

I added jdbc4.jar in Libraries/Compile

SQL Server Browser windows service is running.

In SQL Server Network Configuration i selected Enebled on TCP/IP properties.

I Set TCP Address to 1433.

On Run,VM Options i put -Djava.library.path=my path to sqljdbc_auth.dll And copy in JDk ,in bin sqljdbc_auth.dll.

What should I do?

EDIT: When write in cmd telnet localhost 1433 i get 'Could not open connection to the host,on port 1433'

like image 827
Blocked Avatar asked May 21 '13 18:05

Blocked


1 Answers

If using Window authentication you can do something like:

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);

and then add the path to sqljdbc_auth.dll as a VM argument (you need sqljdbc4.jar in the build path).

Take a look here for a short step-by-step guide showing how to connect to SQL Server from Java should you need more details. Hope it helps!

like image 67
Thusi Avatar answered Oct 05 '22 08:10

Thusi