日期:2014-05-20 浏览次数:20981 次
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestJDBC { /** * @param args */ /**jdbc:sqlserver://localhost:1433;databaseName=bbsDB;user=Lenovo;password=123456" * @param args */ public static void main(String[] args) { Connection con=null; Statement stmt=null; ResultSet rs=null; try{ //jdbc:sqlserver://localhost:1433;databaseName=bbsDB;user=Lenovo;password=123456 //jdbc:sqlserver://localhost;user=MyUserName;password=*****; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con=DriverManager.getConnection("jdbc:sqlserver://localhost;user=Lenovo;password=123456"); stmt=con.createStatement(); rs=stmt.executeQuery("Select * from bbsUsers "); while(rs.next()){ //得到内容 rs.getString("UserName"); } }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); } finally{ try{ if(con!=null){ con.close(); con=null; } if(stmt!=null){ stmt.close(); stmt=null; } if(rs!=null){ rs.close(); rs=null; } }catch(SQLException e){ e.printStackTrace(); } } } }
com.microsoft.sqlserver.jdbc.SQLServerException: 通过端口 1433 连接到主机 localhost 的 TCP/IP 连接失败。错误:“Connection refused: connect。请验证连接属性,并检查 SQL Server 的实例正在主机上运行,且在此端口接受 TCP/IP 连接,还要确保防火墙没有阻止到此端口的 TCP 连接。”。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171) at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1033) at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817) at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700) at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842) at java.sql.DriverManager.getConnection(DriverManager.java:582) at java.sql.DriverManager.getConnection(DriverManager.java:207) at TestJDBC.main(TestJDBC.java:24)