Connect to an SQL Server instance

更新时间:
复制 MD 格式

After the initial configuration, you can connect to your SQL Server instance by using methods such as Data Management (DMS) or SQL Server Management Studio (SSMS). This topic describes the steps for each method.

Prerequisites

  • You have created an ApsaraDB RDS for SQL Server instance. For more information, see Create an ApsaraDB RDS for SQL Server instance.

  • You have created a database and an account. For more information, see Create a database and an account.

  • You have configured an IP address whitelist to allow your client, such as an Elastic Compute Service (ECS) instance or an on-premises device, to access the ApsaraDB RDS for SQL Server instance. For more information, see Configure an IP address whitelist.

    Note
    • If you use an Elastic Compute Service (ECS) instance to connect to an ApsaraDB RDS for SQL Server instance over an internal network, the ECS instance and the RDS instance must be in the same region and the same virtual private cloud (VPC). Add the private IP address of the ECS instance to the IP address whitelist.

    • If you use an on-premises device to connect to an ApsaraDB RDS for SQL Server instance, you must add the public IP address of the device to the IP address whitelist.

Procedure

You can use DMS, a client, or a Java application to connect to the SQL Server database.

Use DMS

Data Management (DMS) is a one-stop data management platform that supports the entire data lifecycle. It provides features such as global data asset management, data governance, database design and development, data integration, data development, and data consumption. The built-in Database Backup Service (DBS) also provides low-cost and highly reliable backup and recovery capabilities. DMS is designed to help enterprises efficiently and securely unlock the value of their data and accelerate their digital transformation.

You can use DMS to log on to an RDS for SQL Server instance without configuring an IP address whitelist or selecting a connection type.

  1. Go to the Instances page. In the top navigation bar, select the region in which the RDS instance resides. Then, find the RDS instance and click the ID of the instance.

  2. Click Log On to Database to open the DMS logon page.

    image..png

  3. In the Log on to Database Instance dialog box, enter your credentials and click Log In.

    image

    • Select an Access Mode. This tutorial uses Account + password login as an example.

    • Enter the Database Account and Database Password. This tutorial uses the privileged account testuser and a custom password as an example.

    • Select a Control Mode. This tutorial uses Flexible Management as an example.

      Note
      • The Flexible Management mode is free of charge. The Stable Change and Security Collaboration modes incur fees.

      • Unlike the Flexible Management Control Mode, the Stable Change and Security Collaboration modes offer more features and greater control over the database. If you are trying out an RDS for SQL Server instance, we recommend that you select the Flexible Management mode.

  4. View the database. After you log on, you can find the new database in the Instances Connected section in the left-side navigation pane of the DMS console. This tutorial uses the dbtest database as an example. You can also double-click other databases to switch between them.

    image

    Note

    If the instance exists but the target database is not displayed in the list of connected instances in DMS, the possible causes are:

    • The logon account does not have permissions to access the target database: You can go to the Accounts page of the RDS instance, find the target account, and click Change Permissions in the Actions column to grant permissions.

    • The database tree is not displayed because the metadata is out of sync: Move the pointer over the instance to which the target database belongs and click the image icon next to the instance name to refresh the database list and display the target database.

  5. After you log on to the SQL Server database in DMS, you can create databases, create tables, query data, and modify table data on the SQL Console tab.

Use SSMS

Microsoft SQL Server Management Studio (SSMS) is a graphical user interface (GUI) tool used to manage and administer SQL Server. You can use it to connect to various SQL Server databases, including RDS for SQL Server instances, on-premises SQL Server instances, or SQL Server instances in other clouds.

This tutorial shows how to connect to an RDS for SQL Server instance by using Microsoft SQL Server Management Studio 19.0 (SSMS).

Note
  • We recommend that you download the latest client version to ensure support for all SQL Server versions.

  • To connect to an instance by using a client, you must first configure an IP address whitelist and obtain the instance endpoint.

  1. Start Microsoft SQL Server Management Studio 19.0 (SSMS) on your local computer.

  2. Choose Connection > Database Engine.

  3. In the Connect to Server dialog box, enter the credentials.

    Parameter

    Value

    Description

    Server name

    rm-2ze****.rds.aliyuncs.com,1433

    The endpoint and port of the RDS instance. Enter the Public Address and Outside the network port that you obtained. Separate the endpoint and port with a comma (,).

    Authentication

    SQL Server Authentication

    The authentication method for SQL Server.

    Username

    testuser

    The username for the RDS instance account.

    Password

    Test_pw123

    The password for the RDS instance account.

  4. Click Connection.

    After a successful connection, the database connection information is displayed in the left-side navigation pane of SSMS.

Use a Java application

This section shows how to connect to an RDS for SQL Server instance from a Java application by using Java Database Connectivity (JDBC).

Note

Before you connect to the database, add the IP address of the environment where the application runs (such as an ECS instance or an on-premises device) to the IP address whitelist of the RDS for SQL Server instance. For more information, see Configure an IP whitelist.

  1. In your Maven project, add the Microsoft JDBC driver for SQL Server.

    Method 1: Manually add the dependency to the pom.xml file

    Note
    • We recommend that you select a dependency version based on the Java version. For example, the mssql-jdbc-12.2.0.jre8.jar file in the 12.2.0 package should be used with Java 8 or later.

    • For information about how to view historical versions of the dependency, see the official documentation.

    <dependency>
      <groupId>com.microsoft.sqlserver</groupId>
      <artifactId>mssql-jdbc</artifactId>
      <version>12.2.0.jre8</version> <!-- Check for the latest version. -->
    </dependency>

    image

    After you add the dependency, click image. The dependency in the pom.xml file is automatically downloaded.

    image

    Method 2: Manually download the JDBC driver and add it to the classpath of the Maven project

    1. Download a driver that matches your Java version from Microsoft JDBC Driver for SQL Server.

      Microsoft JDBC Driver for SQL Server is a Type 4 JDBC driver that provides database connectivity through the standard JDBC application programming interfaces (APIs) available on the Java platform. It provides access to SQL Server from any Java application, application server, or Java-enabled applet.
    2. After you download and decompress the driver, manually save the JAR file (for example, sqljdbc4.jar or sqljdbc.jar) to your project.

      This tutorial uses IntelliJ IDEA as an example to demonstrate how to add the file:

      image

      image

      image

  2. Write sample code to connect to a SQL Server database by using Java, as shown in the following example:

    Replace the endpoint, database name, username, password, and SQL statement in the sample code with actual values. For more information, see View or modify endpoints and ports.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.ResultSet;
    
    public class testMSSQLJDBC {
    
        public static void main(String[] args) {
            // Specify the database endpoint. Use the internal endpoint if your application is deployed on an ECS instance. Use the public endpoint if it is deployed on-premises or in another environment.
            String url = "jdbc:sqlserver://rm-2vc367d081200******.mssql.cn-chengdu.rds.aliyuncs.com:1433;"
                    + "database=YourDatabaseName;"
                    + "encrypt=true;"
                    + "trustServerCertificate=true;"
                    + "loginTimeout=30;";
            // If you do not use Windows Authentication, you must specify a username and password.
            String username = "usernametest";
            String password = "Passwordtest!";
    
            // Create a connection object.
            Connection connection = null;
    
            try {
                // Load the JDBC driver.
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                // Establish a connection to the SQL Server database.
                connection = DriverManager.getConnection(url, username, password);
                System.out.println("Connection successful!");
    
                // Create a Statement object to execute SQL statements.
                Statement statement = connection.createStatement();
                // Execute the SQL query. Replace the table name and column names with your actual information.
                String sql = "SELECT TOP 10 * FROM YourTableName";
                ResultSet resultSet = statement.executeQuery(sql);
    
                // Process the result set.
                while (resultSet.next()) {
                    System.out.println("Column 1: " + resultSet.getString("YourColumnName1"));
                    System.out.println("Column 2: " + resultSet.getString("YourColumnName2"));
                }
    
                // Close the result set.
                resultSet.close();
                // Close the Statement object.
                statement.close();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // Close the connection.
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
  3. Test the connection.

    Save the code as a SqlServerConnection.java file. Compile and run the program from the command line or in an IDE. If the configuration is correct, the program produces output similar to the following, which indicates a successful connection to the SQL Server database.

    image

Troubleshoot connection failures

For more information, see Troubleshoot connection issues.

FAQ

I want to connect to an RDS instance by using a public endpoint, but my public IP address is unstable and keeps changing. What do you suggest?

We recommend that you add a larger CIDR block to the IP address whitelist to meet your business requirements. For more information, see Configure an IP address whitelist and How do I determine the public IP address of an external server or client for SQL Server?.

Important

0.0.0.0/0 indicates that any IP address can access the RDS instance. If you add 0.0.0.0/0 to the IP address whitelist for testing, modify this entry immediately after the test is complete.

I use Function Compute and want to retrieve data from RDS. How can I do this?

You can install third-party dependencies for your function and use built-in modules to retrieve data from RDS. For more information, see Install third-party dependencies for a function.

I logged on to an RDS instance in DMS, but DMS indicates that no database is found. Why?

If the target database is not in the Instances Connected list, check for the following issues:

  • The logon account does not have permissions to access the target database: Go to the Accounts page of the RDS instance details page. Find the target account and click Change Permissions in the Actions column to grant permissions. For more information, see Modify the permissions of an account.

  • The directory is not displayed because metadata is not synchronized: Hover the pointer over the instance to which the target database belongs and click the image icon to the right of the instance name. This refreshes the database list and displays the target database.

I cannot connect to my RDS instance from my on-premises computer by using SSMS. Why?

To connect to an ApsaraDB RDS for SQL Server instance from an on-premises SSMS client, make sure that the following requirements are met:

  • To access the RDS instance from an on-premises device, you must apply for a public endpoint and use it to connect to the instance. You are not charged for applying for a public endpoint or for the subsequent public traffic that is generated. For more information, see Apply for a public endpoint.

    In the left-side navigation pane of the instance details page, click Database Connection to view the instance's internal endpoint, public endpoint, and port number (1433 by default). A public endpoint looks similar to rm-<instance_id>.mssql.<region>.rds.aliyuncs.com. Before connecting, click Set Whitelist next to the public endpoint to add the IP address of your application server or on-premises device to an IP address whitelist. When you use SQL Server Management Studio to connect, enter the server name in the <public_endpoint>,1433 format.

  • Add the public IP address of your on-premises device to the instance's IP address whitelist. For more information, see Add an IP address whitelist for an RDS instance.

    To do this, go to the instance management page and click Whitelist and Security Group in the left-side navigation pane. On the Whitelist Settings tab, click Add Whitelist Group.

I failed to log on to an RDS instance from the DMS client, even though the password and other information are correct. What should I do?

We recommend that you log on to the RDS instance from the DMS web console as described in Method 1, instead of using the DMS client. If a logon error occurs, see FAQ about logging on to a database by using DMS for solutions.