
# 基于Python的Hive样例程序
#### 功能介绍
本章节介绍如何使用Python连接Hive执行数据分析任务。
#### 样例代码
使用Python方式提交数据分析任务，参考样例程序中的"hive-examples/python-examples/pyCLI_sec.py"。
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/devg3-mrs/public_sys-resources/note_3.0-zh-cn.png)
   如果HiveServer实例被迁移，原始的示例程序会失效。在HiveServer实例迁移之后，用户需要更新示例程序中使用的HiveServer的IP地址。
   
3. 在HAConnection的第三个参数填写正确的用户名，密码可以不填写。创建连接，执行HQL，样例代码中仅执行查询所有表功能，可根据实际情况修改HQL内容，输出查询的列名和结果到控制台。
   ```
   try:
       with HAConnection(hosts = hosts,
                          port = 10000,
                          authMechanism = "PLAIN",
                          user='root',
                          password='******') 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
   ```
   
 
