connecting to local MS SQL Server

Mike picture Mike · May 9, 2012 · Viewed 23k times · Source

I have a local MS SQL Server and I am trying to connect to it using JTDS in java. Here is the connection string:

Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/stock","sa","password");

And the server properties:
name: USER-PC\SQLEXPRESS
root directory: c:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL

I am getting a Exception in thread "main" java.sql.SQLException: Network error IOException: Connection refused: connect error.

How can I remedy this?

Answer

Martin Wilson picture Martin Wilson · May 9, 2012

Check the following:

  • You have enabled mixed mode security, i.e. so you can connect with username/password (rather than using Windows authentication)
  • The TCP/IP protocol is enabled. Open SQL Server Configuration Manager, then in SQL Server Network config select Protocols and Enable TCP/IP.
  • Try passing just one String to getConnection using this format:

    DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/stock;instance=SQLEXPRESS;user=sa;password=password")
    
  • If you are using this format (naming the instance) then the SQL Server Browser service needs to be running (in Services). If this is greyed out then the Service is probably disabled, so enable it and then start it.