如何设置从eclipse到SQLServer的连接?

时间:2013-12-02 21:16:33

标签: sql sql-server eclipse

我正在尝试从eclipse连接到SQL Server,我收到以下错误。我提到我已验证并且SQL Server Browser正在主机上运行,​​并且我没有激活防火墙。

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.

这是我写的代码:

   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);

    }

}

2 个答案:

答案 0 :(得分:3)

DB编程之前的第一件事。测试每个“步骤”。在执行任何查询甚至编写任何其他代码之前,请检查您是否可以连接到数据库。我假设您正在连接到本地数据库。有关制作连接网址的步骤,请参阅 - http://technet.microsoft.com/en-us/library/ms378428.aspx

尝试将您的URL更改为 - jdbc:sqlserver:// localhost; user = Mine; password = Secret; databaseName = MyDB。我尝试了这段代码并且有效。

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);

    }

}

答案 1 :(得分:0)

只需启用/启动 SQL Server 浏览器并将 sqljdbc_auth.dll 文件复制到 Windows->System32,方法是从 (Microsoft jdbc driver 9.2 for sql server) 中提取此文件