Main Content

Microsoft SQL Server JDBC for Windows

This tutorial shows how to set up a data source and connect to a Microsoft® SQL Server® database using the Database Explorer app or the command line. This tutorial uses the Microsoft JDBC Driver 4.0 for Microsoft SQL Server to connect to a Microsoft SQL Server 2016 Express database.

Step 1. Verify the driver installation.

If the JDBC driver for Microsoft SQL Server is not installed on your computer, find the link on the Driver Installation page to install the driver. Follow the instructions to download and install this driver on your computer.

Step 2. Verify the port number.

Complete the following steps on the machine where SQL Server is installed to find your port number for database connection. If you experience connection issues with the port number that you find, contact your database administrator.

  1. On the machine where your SQL Server database is installed, click Start. Select your Microsoft SQL Server version folder and click SQL Server Configuration Manager.

    Sql Server Configuration Manager dialog box

  2. On the left of the Sql Server Configuration Manager window, click SQL Server Network Configuration. Double-click Protocols for SQLEXPRESS.

  3. See if TCP/IP is enabled. If so, skip steps 4 and 5.

  4. If TCP/IP is disabled, right-click TCP/IP and select Enable.

    Sql Server Configuration Manager dialog box with the selected TCP/IP protocol and the Enable option selected in the context menu

  5. To finish the process of enabling the TCP/IP protocol, restart the server. On the left side of the window, click SQL Server Services. Right-click SQL Server (SQLEXPRESS) and click Restart. The server restarts, enabling TCP/IP.

    Sql Server Configuration Manager dialog box with the selected SQL Server (SQLEXPRESS) service and the Restart option selected in the context menu

  6. Click Protocols for SQLEXPRESS and right-click TCP/IP. Select Properties.

  7. In the TCP/IP Properties dialog box, scroll to the bottom on the IP Addresses tab until you see the IPAll group. The number next to TCP Dynamic Ports is the port number. Use this port number in the JDBC Data Source Configuration dialog box when configuring a data source using the Database Explorer app. Or, enter this port number as an input argument of the database function at the command line. Here, the port number is 53917. If this number is 0 or if you want to configure your SQL Server database server to listen to a specific port, delete the entry in the TCP Dynamic Ports box. Then, enter another port number in the TCP Port box.

    TCPI/IP Properties dialog box

  8. Click Apply and click OK to close the TCP/IP Properties dialog box. Then, close the Sql Server Configuration Manager dialog box.

Step 3. Set up the operating system authentication.

Windows® authentication enables you to connect to a database using your Windows user account. In this case, Windows performs user validation, and the database does not require a different user name and password. Windows authentication facilitates the maintenance of database access credentials. After you add the required libraries to the system path, the Microsoft SQL Server JDBC driver enables connectivity using Windows authentication. The following steps show how to add these libraries to the Java® library path in MATLAB®. For details about Java libraries, see Java Class Path.

  1. Ensure that you have the latest Java driver library installed on your computer. To install the latest library, see Driver Installation.

  2. Run the prefdir function in the Command Window. The output of this command is a file path to the MATLAB preferences folder on your computer. For details, see prefdir.

  3. Close MATLAB.

  4. Navigate to the folder from step 2, and create a file named javalibrarypath.txt in the folder.

  5. Open javalibrarypath.txt and insert the path to the Java library file sqljdbc_auth.dll. This file is installed in the following location:

    <installation>\sqljdbc_<version>\<language>\auth\<arch>
    

    <installation> is the installation folder of the Microsoft SQL Server JDBC driver, <version> is the JDBC driver version, <language> is the JDBC driver language, and <arch> is the architecture.

    Use the x64 folder. In the entry, include the full path to the library file. Do not include the library file name. The following is an example of the path: C:\DB_Drivers\sqljdbc_4.0\enu\auth\x64. Save and close javalibrarypath.txt.

  6. Restart MATLAB.

Step 4. Set up the data source.

You set up a data source using the Database Explorer app or the command line.

Set Up Data Source Using Database Explorer App

  1. Open the Database Explorer app by clicking the Apps tab on the MATLAB Toolstrip. Then, on the right of the Apps section, click the Show more arrow to open the apps gallery. Under Database Connectivity and Reporting, click Database Explorer. Alternatively, enter databaseExplorer at the command line.

  2. In the Data Source section, select Configure Data Source > JDBC.

    Configure Data Source selection with the selected Configure JDBC data source

    The JDBC Data Source Configuration dialog box opens.

    JDBC Data Source Configuration dialog box with the selected Microsoft SQL Server vendor

  3. In the Name box, enter a name for your data source. This example uses a data source named MyMicrosoftDataSource. You use this name to establish a connection to your database.

  4. From the Vendor list, select Microsoft SQL Server.

  5. In the Driver Location box, enter the full path to the JDBC driver file.

  6. If you want to store your user credentials for this data source, click the Set Credentials button.

  7. In the Database box, enter the name of your database. In the Server box, enter the name of your database server. Consult your database administrator for the name of your database server. In the Port Number box, enter the port number.

  8. To establish the data source with Windows authentication, set Authentication to Windows.

    Or, to establish the data source without Windows authentication, set Authentication to Server.

  9. Under Connection Options, in the Name column, enter the name of an additional driver-specific option. Then, in the Value column, enter the value of the driver-specific option. Click the plus sign + to specify additional driver-specific options.

  10. Click Test.

    • If you stored your user credentials using the Set Credentials button, the Database Explorer app attempts to make the connection without Windows authentication.

    • If you have not stored your credentials, the Test Connection dialog box opens. Enter the username and password for your database. If you are connecting with Windows authentication, then leave these boxes blank. Click Test.

    If your connection succeeds, the Database Explorer dialog box displays a message indicating the connection is successful. Otherwise, it displays an error message.

  11. Click Save. The JDBC Data Source Configuration dialog box displays a message indicating the data source is saved successfully. Close this dialog box.

Set Up Data Source Using Command Line

  1. Create a JDBC data source for an SQL Server database.

    vendor = "Microsoft SQL Server";
    opts = databaseConnectionOptions("jdbc",vendor);
  2. Set the JDBC connection options. To set the connection options with Windows authentication, use the 'AuthenticationType' name-value argument. For example, this code assumes that you are connecting to a JDBC data source named MSSQLServer, full path of the JDBC driver file C:\Drivers\sqljdbc4.jar, database name toystore_doc, database server dbtb04, port number 54317, and authentication type Windows.

    opts = setoptions(opts, ...
        'DataSourceName',"MSSQLServer", ...
        'JDBCDriverLocation',"C:\Drivers\sqljdbc4.jar", ...
        'DatabaseName',"toystore_doc",'Server',"dbtb04", ...
        'PortNumber',54317,'AuthenticationType',"Windows");
    

    To set the connection options without Windows authentication, omit the 'AuthenticationType' name-value argument.

  3. For a data source with Windows authentication, test the database connection by leaving the username and password blank.

    username = "";
    password = "";
    status = testConnection(opts,username,password);

    To test without Windows authentication, specify a username and password. When specifying your user credentials, the recommended practice is to store them in your MATLAB vault using setSecret instead of including them in your code. Retrieve your credentials by using the getSecret function.

    Before R2024a: setSecret and getSecret are not available. Specify your username and password using character vectors or strings.

    setSecret("usernamemssql");
    setSecret("passwordmssql");
    status = testConnection(opts,getSecret("usernamemssql"),getSecret("passwordmssql"));
  4. Save the JDBC data source.

    saveAsDataSource(opts)

After you complete the data source setup, connect to the SQL Server database using the Database Explorer app or the JDBC driver and command line.

Step 5. Connect using the Database Explorer app or the command line.

Connect to SQL Server Using Database Explorer App

  1. On the Database Explorer tab, in the Connections section, click Connect and select the data source for the connection.

    • If you stored your user credentials using the Set Credentials button, the Database Explorer app makes the connection and the Catalog and Schema dialog box opens.

    • If you have not stored your user credentials, the connection dialog box opens. If you create a connection with Windows authentication, leave the Username and Password boxes blank in the connection dialog box, and click Connect. Otherwise, enter your username and password and click Connect and the Catalog and Schema dialog box opens.

  2. Select the catalog and schema from the Catalog and Schema lists. Click OK.

    The app connects to the database and displays its tables in the Data Browser pane. A data source tab appears to the right of the pane. The title of the data source tab is the data source name that you defined during the setup. The data source tab contains empty SQL Query and Data Preview panes.

  3. Select tables in the Data Browser pane to query the database.

  4. Close the data source tab to close the SQL query. In the Connections section, close the database connection by clicking Close Connection.

    Note

    If multiple connections are open, close the database connection of your choice by selecting the corresponding data source from the Close Connection list.

Connect to SQL Server Using JDBC Driver and Command Line

  1. To connect with Windows authentication, use the configured JDBC data source and specify a blank username and password. For example, this code assumes that you are connecting to a JDBC data source named MSSQLServerAuth.

    datasource = "MSSQLServerAuth";
    username = "";
    password = "";
    conn = database(datasource,username,password);

    To connect without Windows authentication, use the configured JDBC data source and specify the username and the password. For example, this code assumes that you are connecting to a JDBC data source named MSSQLServer.

    datasource = "MSSQLServer";
    setSecret("usernamemssql");
    setSecret("passwordmssql");
    conn = database(datasource,getSecret("usernamemssql"),getSecret("passwordmssql"));
  2. Close the database connection.

    close(conn)

See Also

Apps

Functions

Related Topics