4

I am running this code snippet on localhost in windows authentication but getting following error but I have alreadily added sqljdbc4 jar in my class path and while running from eclipse also I have added jar in build path

import java.io.*;
import java.sql.*;
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

class  Cms_truncate
{
    public static void main(String[] args) 
    {
         Calendar cal = new GregorianCalendar();

         //String name="cmscim";
                 Connection conn = null;

         String url = "jdbc:sqlserver://localhost\SQLEXPRESS;databasename=yatin";
         String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
         String userName = ""; 
         String password = "";
         Statement stmt;
         try
         {

         Class.forName(driver);//.newInstance();
         conn = DriverManager.getConnection(url,userName,password);
         String query = "truncate table cim";
         stmt = conn.createStatement();
         int flag = stmt.executeUpdate(query);
         System.out.println("flag = "+flag); 
         conn.close();
        System.out.println("");
         } catch (Exception e) {
         e.printStackTrace();
         }

    }
}

The Error:

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)
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
    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(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at Cms_truncate.main(Cms_truncate.java:28)

help me please.

Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
yatinbc
  • 605
  • 3
  • 16
  • 37
  • 2
    *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.* - That says it all, check if the instance is running at specified port and it is accepting connection request, check if the credentials are correct! – AllTooSir Apr 20 '13 at 16:27
  • Check this:http://stackoverflow.com/questions/11820799/com-microsoft-sqlserver-jdbc-sqlserverexception-the-tcp-ip-connection-to-the-ho – AllTooSir Apr 20 '13 at 16:28
  • Don't forget to check the firewall too! – JStrahl Aug 10 '15 at 14:00

5 Answers5

10

This error does not say "authentication error", it says "connection error" due to a "connection refused". This means you need to specify the correct port number. You'll need to review your SQL Server configuration and update your connection string.

according to MSDN docs, the connection string should look like this:

jdbc:sqlserver://localhost:<insert_proper_port_here>\SQLEXPRESS;databasename=yatin

You are not supplying a username or password, which you might need to do once you get the port number figured out. See the referenced documentation for further details.

PaulProgrammer
  • 16,175
  • 4
  • 39
  • 56
4

I think it is configuration issue.

Go to Run -> SQL Server Configuration Manger

Expand -> SQL Server *version_no* Network Configuration

Then click on - "Protocol for SQLEXPRESS"

If you find TCP/IP protocol with Disabled status then you need to enable it.

In addition, you will need to restart the service: Open cmd > type in Services, then scroll down to SQL Server(MSSQLServer), and restart the service

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Shekhavat
  • 110
  • 1
  • 7
4

First of all whenever you are using SQL instance name in URL you have to specify //[serverName[\\instanceName][:portNumber]]databaseName

for E.g: jdbc:sqlserver://localhost\\SQLEXPRESS:1433;databasename=yatin

Once this is done next step:-

  1. Go to all Program- > search for SQL Server Configuration Manager.Open it
  2. Expand SQL server network configuration in left pane
  3. Click on protocols for instance name in most cases it would be protocols for SQLEXPRESS
  4. Click on TCP IP. TCP IP properties window will get opened
  5. Select enabled property and listen all property as "YES"
  6. Navigate to IP address tab and check if ip all section TC Dynamic port is 1433 if not then set it
  7. Then Apply and ok

  8. Now go to SQL server services section under SQL Server Configuration Manager in left pane. click on it

  9. You will see database engine is running one with instance name in most of the case SQLEXPRESS,right click on it and stop it and then start it again.

Now rerun the code

Vasfed
  • 18,013
  • 10
  • 47
  • 53
TShetty
  • 41
  • 1
  • Small correction. here, you have mentioned to change "TCP dynamic port". but actually, we have to change the TCP Port, not TCP Dynamic port. Happy Coding. – Bandham Manikanta Jul 15 '18 at 07:28
2

You forgot to mention instance name. See Building the Connection URL explain how to use connection url in sqlserver

If you not mention the full servername then you get the error like

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.".

My Server name is V_UDAY\FRAMEWORK,I removed FRAMEWORK instance in URL(in Java code) and execute, then I got an error as below.

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host V_UDAY, 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)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
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:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.testsql.SqlServerDatabaseConnectionUsingJava.getLocalConnection(SqlServerDatabaseConnectionUsingJava.java:28)
at com.testsql.SqlServerDatabaseConnectionUsingJava.main(SqlServerDatabaseConnectionUsingJava.java:18)
Exception in getLocalConeection() The TCP/IP connection to the host V_UDAY, 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.".

Below Image shown you server name with slash seperation

SQLSERVER_LoginPage

sqljdbc4 is required for executing below Java program. Download sqljdbc4 jar or from Microsoft JDBC Driver 4.0 for SQL Server .

Example for connect to sqlserver using Java. Here JSF is database name.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SqlServerDatabaseConnectionUsingJava {
    private static Connection connection = null;
    //1.jdbc driver name
    private static String SQL_JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    // 2. Database URL, V_UDAY\FRAMEWORK is ServerName and JSF is DataBase name
    private static String URL = "jdbc:sqlserver://V_UDAY;instanceName=FRAMEWORK;databaseName=JSF";
    //3.Database credentials
    private static String USERNAME = "udaykiran";//UserName
    private static String PASSWORD = "Pa55word";//Password

public static void main(String[] args) {
    getLocalConnection();
}

public static Connection getLocalConnection() {
    try {
        Class.forName(SQL_JDBC_DRIVER);// Register jdbc driver

        System.out.println("****Connect to Database****");

        //4. open a connection
        connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        System.out.println("DataBase connect to: "+ connection.getMetaData().getDriverName());
        System.out.println("URL: "+ connection.getMetaData().getURL());

        setConnectionClose();
        System.out.println("Database Connection Closed");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Exception in getLocalConeection() "+e.getMessage());
    }
    return connection;
}

public static void setConnectionClose() throws SQLException {
    if (connection != null) {
        connection.close();
    }
}

}

Note: Mention instance name FRAMEWORK in connection url if you have otherwise remove instance name.

UdayKiran Pulipati
  • 6,579
  • 7
  • 67
  • 92
0

According Microsoft Documentation

String url = "jdbc:sqlserver://localhost\SQLEXPRESS:[your_port_tcp];databasename=yatin";

https://msdn.microsoft.com/pt-br/library/ms378428(v=sql.110).aspx

josliber
  • 43,891
  • 12
  • 98
  • 133