Skip to content
Advertisement

How to set a connection from eclipse to SQLServer?

I am trying to connect to SQL Server from eclipse and i get the following error. I mention that i verified and the SQL Server Browser is running on the host and i have no firewall active.

com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host 
LAURA-PC, 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.

This is the code i’ve written:

   import java.sql.*;


public class ConnectSQLServer {

    public void connect(String url){
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            Connection connection = DriverManager.getConnection(url);
            System.out.println("Connected");
            Statement statement = connection.createStatement();
            String query = "select * from Vehicle where Mileage < 50000";
            ResultSet rs = statement.executeQuery(query);
            while(rs.next()){
                System.out.println(rs.getString(1));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        ConnectSQLServer connServer = new ConnectSQLServer();
        String url = "jdbc:sqlserver://LAURA-PC\SQLEXPRESS;databaseName=Register;integratedSecurity=true";
        connServer.connect(url);

    }

}

Advertisement

Answer

First thing before DB programming. Test each “step”. Before executing any query or even writing any other code, please check if you can connect to the DB. I assume that you are connecting to the local db. For steps on making your connection URL, see – http://technet.microsoft.com/en-us/library/ms378428.aspx

Try changing your URL to – jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=MyDB. I tried this code and it worked.

import java.sql.*;


public class ConnectSQLServer {

    public void connect(String url){
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            Connection connection = DriverManager.getConnection(url);
            System.out.println("Connected");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        ConnectSQLServer connServer = new ConnectSQLServer();
        String url = "jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=AdventureWorks";
        connServer.connect(url);

    }

}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement