gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:02:47 31 4
gpt4 key购买 nike

我正在尝试从 Eclipse 连接到 SQL Server,但出现以下错误。我提到我已验证并且 SQL Server 浏览器正在主机上运行,​​并且我没有激活防火墙。

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

}

}

最佳答案

数据库编程之前的第一件事。测试每个“步骤”。在执行任何查询甚至编写任何其他代码之前,请检查您是否可以连接到数据库。我假设您正在连接到本地数据库。有关制作连接 URL 的步骤,请参阅 - 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);

}

}

关于sql - 如何设置从 eclipse 到 SQLServer 的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20338004/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com