Thursday 15 June 2017

Connect to SAP HANA via JDBC

SAP HANA provides a driver that enables Java applications to connect to the SAP HANA database with the JDBC application programming interface (API).

 ◈  Procedure


1. Install the JDBC driver.

SAP HANA, JDBC, All SAP Modules

The driver (ngdbc.jar) is installed as part of the SAP HANA client installation and by default is located at:
  • C:\Program Files\sap\hdbclient\ on Microsoft Windows platforms
  • /usr/sap/hdbclient/ on Linux and UNIX platforms
2. Add ngdbc.jar to your classpath.

3. Write Java code to create a connection to the database and execute SQL commands. Use a connection string in the form of jdbc:sap://<server>:<port>[/?<options>]. For example:

jdbc:sap://myServer:30015/?autocommit=false

Specify one or more failover servers by adding additional hosts, as in the following example:

jdbc:sap://myServer:30015;failover1:30015;failover2:30015/?autocommit=false

To connect to a specific database, for example tdb1, use the databaseName parameter, as illustrated in the following code:

jdbc:sap://localhost:30013/?databaseName=tdb1&user=SYSTEM&password=manager

◈ Example


The following is an example of connecting to an SAP HANA server called myhdb, which was installed as instance 07, with user name myName and password mySecret. Make sure to change these for your system, and add the JDBC driver (ngdbc.jar) to your classpath.

import java.sql.*;
public class jdemo {
   public static void main(String[] argv) {
      Connection connection = null;
      try {          
         connection = DriverManager.getConnection(
            "jdbc:sap://myhdb:30715/?autocommit=false", "myName", "mySecret");          
      } catch (SQLException e) {
         System.err.println("Connection Failed:");
         System.err.println(e);
         return;
      }
      if (connection != null) {
         try {
            System.out.println("Connection to HANA successful!");
            Statement stmt = connection.createStatement();
            ResultSet resultSet = stmt.executeQuery("Select 'hello world' from dummy");
            resultSet.next();
            String hello = resultSet.getString(1);
            System.out.println(hello);
       } catch (SQLException e) {
          System.err.println("Query failed!");
       }
     }
   }
}
SAP Online Guides, Tutorials, Materials and Certifications.

Related Posts

3 comments: