Export (0) Print
Expand All

How to: Connect to Azure SQL Database Using JDBC

Updated: November 21, 2014

You can connect to Microsoft Azure SQL Database by using Java and the Microsoft SQL Server JDBC Driver starting with version 3.0. This topic shows how to create a Java application that connects to Azure SQL Database. Follow the steps in the System Requirements for the JDBC Driver section of the Microsoft SQL Server JDBC Driver documentation to prepare your computer for developing with Java and Azure SQL Database.

Prepare the Development Environment

  1. Download and install the SQL Server JDBC Driver.

  2. To run this sample application, you must set the classpath to include the sqljdbc.jar file or the sqljdbc4.jar file. If the classpath is missing an entry for sqljdbc.jar or sqljdbc4.jar, the sample application will throw the common "Class not found" exception. For more information about how to set the classpath, see Using the JDBC Driver.


In the following example, the sample code sets various connection properties in the connection string and makes a connection to a sample database named School. Then, the sample code executes the SQL statement and iterates through the rows of data that are contained in the result set, and uses the getString method to display some of the data that it contains.

Compile and run this application by using Java command line utilities or your preferred IDE.

import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;

public class ConnectToSQLAzure {

   public static void main(String[] args) {

      // Create a variable for the connection string.
      String connectionUrl = "jdbc:sqlserver://servername.database.windows.net;" +
      // Declare the JDBC objects.
      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;

      try {
         // Establish the connection.
         con = DriverManager.getConnection(connectionUrl);

         // Create and execute an SQL statement that returns some data.
         String SQL = "SELECT TOP 10 * FROM dbo.Person";
         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(2) + " " + rs.getString(3));

      // Handle any errors that may have occurred.
      catch (Exception e) {
      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) {}

See Also

Community Additions

© 2015 Microsoft