在 SQL Server 2005 里面,如果出现到主机 的 TCP/IP 连接失败。 java.net.ConnectException: Connection refused: connect!
估计是因为sqlserver2005默认情况下是禁用了tcp/ip连接。
您可以在命令行输入:telnet localhost 1433进行检查,这时会报错:正在连接到localhost...不能打开到主机的连接,在端口 1433: 连接失败 启动tcp/ip连接的方法:
打开 /Microsoft SQL Server 2005/配置工具/目录下的SQL Server Configuration Manager,选择mssqlserver协议, 然后右边窗口有个tcp/ip协议,然后启动它,把sqlserver服务停了,然后在启动。问题就解决了! 这时在命令行输入:telnet localhost 1433就不会再报错了,窗口显示为一片黑,即为正常。
代码:
//=====================================================================
//
// File: connectURL.java
// Summary: This Microsoft SQL Server 2005 JDBC Driver sample application
// demonstrates how to connect to a SQL Server database by using
// a connection URL. It also demonstrates how to retrieve data
// from a SQL Server database by using an SQL statement.
// Date: April 2006
//
//---------------------------------------------------------------------
//
// This file is part of the Microsoft SQL Server JDBC Driver Code Samples.
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
//=====================================================================
package mssql;
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:2044;" + //主机名和加端口号,默认是1433.
"user=nono;password=nono123"; //用户名和密码。。。应该不用说了吧
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "select * from test";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(1));
//System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}