首页
登录 | 注册

通过Java JDBC 访问SAP HANA的基本方法

    在编写Java应用时,我们使用jdbc访问数据库。SAP HANA数据库也支持jdbc访问。HANA提供了标准的JDBC类型4驱动,即纯java实现的驱动。因此,只需要在client端部署jar包即可。这篇文章中将结合java示例程序向大家介绍HANA jdbc驱动的基本使用方法。

 一、SAP HANA JDBC Driver
   HANA JDBC Driver的jar包名为ngdbc.jar。
   
   Driver Class:  com.sap.db.jdbc.Driver    
   JDBC URL:    jdbc:sap://192.168.0.199:30015?reconnect=true    

二、java程序示例

package net.db.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

/**
 * JDBC Sample.
 *
 * @author tigeriq123@163.com"> wangbing
 * @version CVS $Revision$ $Date$
 */
public class JDBCDemoHANA {

  
 private static final String DRIVER = "com.sap.db.jdbc.Driver";  //jdbc 4.0
 private static final String URL = "jdbc:sap://192.168.0.199:30015?reconnect=true";

 public JDBCDemoHANA() {

 }

 
 public static void main(String[] args) {
  JDBCDemoHANA demo = new JDBCDemoHANA();
  try {
   demo.select();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void select() throws Exception {
  Connection con = this.getConnection(DRIVER, URL, "SYSTEM", "Lion12345");
  PreparedStatement pstmt = con.prepareStatement("select USER_ID,USER_NAME,USER_MODE from SYS.USERS");
  ResultSet rs = pstmt.executeQuery();
  this.processResult(rs);
  this.closeConnection(con, pstmt);

 }

 private void processResult(ResultSet rs) throws Exception {
  if (rs.next()) {
   ResultSetMetaData rsmd = rs.getMetaData();
   int colNum = rsmd.getColumnCount();
   for (int i = 1; i <= colNum; i++) {
    if (i == 1) {
     System.out.print(rsmd.getColumnName(i));
    } else {
     System.out.print("\t" + rsmd.getColumnName(i));
    }

   }
   System.out.print("\n");
   System.out.println("-----------------------");
   do {
    for (int i = 1; i <= colNum; i++) {
     if (i == 1) {
      System.out.print(rs.getString(i));
     } else {
      System.out.print("\t"
        + (rs.getString(i) == null ? "null" : rs
          .getString(i).trim()));
     }

    }
    System.out.print("\n");
   } while (rs.next());
  } else {
   System.out.println("query not result.");
  }

 }

 private Connection getConnection(String driver, String url, String user,
   String password) throws Exception {
  Class.forName(driver);
  return DriverManager.getConnection(url, user, password);

 }

 private void closeConnection(Connection con, Statement stmt)
   throws Exception {
  if (stmt != null) {
   stmt.close();
  }
  if (con != null) {
   con.close();
  }
 }

}


相关文章


2020 unjeep.com webmaster#unjeep.com
12 q. 0.014 s.
京ICP备10005923号