
# 基于Python的Hive样例程序
#### 功能介绍
本章节介绍如何使用Python连接Hive执行数据分析任务。
#### 样例代码
使用Python方式提交数据分析任务，参考样例程序中的"hive-examples/python-examples/pyCLI_sec.py"。该样例程序连接的集群的认证模式是安全模式，运行样例程序之前需要使用**kinit** 命令认证相应权限的Kerberos用户。
1. 导入HAConnection类。
   ```
   from pyhs2.haconnection import HAConnection
   ```
   
2. 声明HiveServer的IP地址列表。本例中hosts代表HiveServer的节点，xxx.xxx.xxx.xxx代表业务IP地址。
   ```
   hosts = ["xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx"]
   ```
   ![](https://support.huaweicloud.com/devg-lts-mrs/public_sys-resources/note_3.0-zh-cn.png)
   如果HiveServer实例被迁移，原始的示例程序会失效。在HiveServer实例迁移之后，用户需要更新示例程序中使用的HiveServer的IP地址。
   
3. 配置Kerberos主机名和服务名。本例中"krb_host"参数值为"hadoop.*实际域名* "，实际域名可登录FusionInsight Manager，选择"系统 \> 权限 \> 域和互信 \> 本端域" 查看；主机名为hadoop，服务名为hive。
   ```
   conf = {"krb_host":"hadoop.<系统域名>", "krb_service":"hive"}
   ```
   
4. 创建连接，执行HQL，样例代码中仅执行查询所有表功能，可根据实际情况修改HQL内容，输出查询的列名和结果到控制台。
   ```
   try: 
          with HAConnection(hosts = hosts, 
                             port = 10000, 
                             authMechanism = "KERBEROS", 
                             configuration = conf) as haConn: 
              with haConn.getConnection() as conn: 
                  with conn.cursor() as cur: 
                      # show databases 
                      print cur.getdatabases() 
                       
                      # execute query 
                      cur.execute("show tables") 
                       
                      # return column info from query 
                      print cur.getschema() 
                       
                      # fetch table results 
                      for i in cur.fetch(): 
                          print i 
                           
      except exception, e: 
          print e
   ```
   
 
