通过Java代码远程连接MS SQL服务器时遇到问题

时间:2015-02-22 07:47:10

标签: java sql-server jdbc-odbc

这是我远程连接服务器的代码。 还有一件事我想告诉大家这个代码只能在我的家庭网络(安装服务器的网络)中工作,但是我无法从其他网络访问它     嘿伙计们请提前感谢

public class SQLServerDemo
{

    public static void main(String[] args)
    {
        // TODO code application logic here

        try {
            System.out.println("Hello from try");

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            String url = "jdbc:sqlserver://192.168.0.2:1433;user=demo;password=demo;databaseName=SQL_Demo";

            Connection conn = DriverManager.getConnection(url);
            if (conn != null)
            {
                System.out.println("Connected");
            } else if (conn == null)
            {
                System.out.println("NotConnected");
            }
            String queryString = "select * from UserDetail";
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(queryString);
            while (rs.next()) {
                System.out.println(rs.getString(1));
                System.out.println(rs.getString(2));
                System.out.println(rs.getString(3));
            }
        }
        catch (Exception e)
        {
                System.out.println("Exception: "+e.getMessage());
                e.printStackTrace();
        }
    }
}    

异常

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host GAUTAM-VAIO, port 1433 has failed.
Error: "null. Verify the connection properties.
Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port.
Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)

1 个答案:

答案 0 :(得分:0)

您不能使用192.168.0.2:1433,它仅在您的内部LAN网络中有效。

您必须从局域网中找到外部IP。