31

I am learning Java and need to just run something simple to retrieve some data from MSSQL via JDBC. The example in my book doesn't work (but it is several years old) and this example below from MS doesn't work for me either:

http://msdn.microsoft.com/en-us/library/ms378956(v=sql.90).aspx

Here's my code:

package javasql;
import java.sql.*;
import java.util.*;

public class Program {

    private static String url = "jdbc:sqlserver://localhost\\SQLExpress;database=Northwind;integratedSecurity=true;";
    //private static String userName = "sa";
    //private static String password = "myPassword";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        RunDemo();
    }

    public static void RunDemo() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection connection = DriverManager.getConnection(url);

            Statement statement = connection.createStatement();
            ResultSet results = statement.executeQuery("SELECT ProductName, Price FROM Products ORDER BY ProductName");

            while(results.next()) {
                System.out.println("Product Name: " + results.getNString("ProductName") + " Price: $" + results.getFloat("UnitPrice"));
            }

        } catch (ClassNotFoundException | SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

When I run the code, I don't get any exceptions thrown.. I just get this in the output window:

run:
com.microsoft.sqlserver.jdbc.SQLServerDriver
BUILD SUCCESSFUL (total time: 0 seconds)

I am using NetBeans 7.2. Please someone give me a working example.

EDIT:

By the way, for the connection string, where you see the \\SQLExpress, I did try removing that and using instanceName=SQLExpress instead.. but that didn't have any effect either.

EDIT 2:

OK, I downloaded the latest JDBC driver for MSSQL from MS and referenced the 2 JAR files in there. Now I'm getting this output:

run:
The connection to the host localhost, named instance SQLExpress failed. 

Error: "java.net.SocketTimeoutException: Receive timed out". 

Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434.  
For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
BUILD SUCCESSFUL (total time: 15 seconds)

Progress.. at least we can see it is trying to connect now, can someone enlighten me as to the above error though?

EDIT 3:

2 more problems fixed.. one is enable SQL Server Browser and the second was enabling TCP/IP for SQL Server. Thanks @Vikdor Now I'm getting this error:

run:
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.".
BUILD SUCCESSFUL (total time: 15 seconds)

I checked windows firewall and added an inbound rule to allow that port, but I'm still getting the above error. Any ideas?

EDIT 4:

Tried the solution in this link: http://www.coderanch.com/t/306316/JDBC/databases/SQLServerException-TCP-IP-connection-host

No longer getting error in EDIT 3. Now getting another...

run:
Sep 21, 2012 11:33:16 AM com.microsoft.sqlserver.jdbc.AuthenticationJNI <clinit>
WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path
This driver is not configured for integrated authentication. ClientConnectionId:577f359e-4774-45f3-96fb-588785911817
BUILD SUCCESSFUL (total time: 14 seconds)

Getting very tired of this now.. why Java, why?? Seriously...I'm glad I work mostly with .NET. Well, when i find the solution, I will post it here to make sure it can help others before they go mad as I am about to...

EDIT 5:

This helped: java connecting to MicrosoftSQLServer 2005

I put the directory path into my PATH environment variable. Didn't work, so I also placed the sqljdbc_auth.dll into my JDK folder C:\Program Files\Java\jdk1.7.0_04\bin. Solved.

Community
  • 1
  • 1
Matt
  • 6,787
  • 11
  • 65
  • 112

8 Answers8

44

OK, so here's what solved my problems:

  1. Download latest MSSQL JDBC driver from here: http://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx

  2. Referenced the 2 JAR files in my project: sqljdbc.jar and sqljdbc4.jar (I'm not yet sure if both of the above are required or just one..)

  3. Make sure the SQL Server Browser windows service is running

  4. Open SQL Server Configuration Manager and go to Protocols for SQLEXPRESS under SQL Server Network Configuration. Right-click on TCP/IP and choose Properties. Set Enabled = YES.

  5. While you're there, click on IP Addresses tab and find the section IP All. Set TCP Port to 1433.

  6. Add sqljdbc_auth.dll to your PATH Environment Variable. In my case: D:\Java\sqljdbc_4.0\enu\auth\x64

  7. Copy the sqljdbc_auth.dll to your JDK directory. In my case: C:\Program Files\Java\jdk1.7.0_04\bin

I hope this helps someone.

Ian R. O'Brien
  • 6,682
  • 9
  • 45
  • 73
Matt
  • 6,787
  • 11
  • 65
  • 112
17

Thanks Finally it's working. If it shows below message as error,

 Verify the server and instance names and check that no firewall is blocking
 UDP traffic to port 1434. For SQL Server 2005 or later,
 verify that the SQL Server Browser Service is running on the host

Please enable Sql Server Browser by,

Start > Control Panel > Systems & Security > Administrative tools > Services

Select SQL Server Browser Right click and select properties.

Set start type as Automatic. Click on Apply > click on start > click on Ok

Make Sure your IPALL TCP Address is - 1433 !

Cnf271
  • 302
  • 5
  • 16
5

In my Case : I wasn't adding the port number in the URL string

String url = "jdbc:sqlserver://ABC\\SQLEXPRESS;databaseName=xyz;portNumber=1433"

it solved my issue

uniqueSolutions
  • 143
  • 2
  • 8
  • That was the point for me. I tried it with ```String url = "jdbc:sqlserver://ABC\\SQLEXPRESS:1433;databaseName=xyz;"``` and got timeout errors – Silvester Schn. Oct 04 '21 at 14:26
4

You may want to check the steps I listed here: Error:The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect and see if the SQLExpress instance is configured correctly, then modify your JDBC URL to specify the instance name separately. The example there is for password-based authentication, but works with your integratedSecurity=true; property.

Community
  • 1
  • 1
Vikdor
  • 23,934
  • 10
  • 61
  • 84
3

Causes :

  1. protocol (TCP/IP) is not enabled
  2. Port is incorrect
  3. missing of sqljdbc_auth.dll
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user3029620
  • 1,179
  • 8
  • 4
2

Named and Multiple SQL Server Instances

If you need to connect from uni* to a named instance, please pay particular attention when you're building the JDBC connection URL

If both a portNumber and instanceName are used, the portNumber will take precedence and the instanceName will be ignored.

This also means that if want use Instance Names you cannot change the port number.

In any of these lines the parameter myinstancename will be ignored:

  • jdbc:sqlserver://db-devmyinstancename;databaseName=mydbname;portNumber=1433
  • jdbc:sqlserver://db-dev;databaseName=dbname;instanceName=myinstancename;portNumber=1433
  • jdbc:sqlserver://db-dev\myinstancename:1433;databaseName=mydbname
  • jdbc:sqlserver://db-dev:1433;databaseName=dbname;instanceName=myinstancename

So if you want use instance names the port number must be removed (tried with jdbc sqlserver drivers ver. 3, 4, 4.1)

freedev
  • 25,946
  • 8
  • 108
  • 125
2

Please enable Sql Server Browser by, Start > Control Panel > Systems & Security > Administrative tools > Services Select SQL Server Browser Right click and select properties.

Set start type as Automatic. Click on Apply > click on start > click on Ok

Make Sure your IPALL TCP Address is - 1433 !

praveen g
  • 21
  • 1
1

It may be silly, but check that your Products table is not empty. Is the only reason I see for no getting any exceptions and no printing anything in the console.

Hernan Velasquez
  • 2,770
  • 14
  • 21