python连接数据库(Redis、Hive、MySQL、HDF5)

1. 连接Redis

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
 
import redis
 
redis_pool = redis.ConnectionPool(host='10.94.220.22', port=6379)
redis_cursor = redis.Redis(connection_pool=redis_pool)
pipe = redis_cursor.pipeline(transaction=True)
 
flag = 'day_' + date
# 存数据
redis_cursor.set(flag, 'OK')
pipe.execute()
print("write to redis done")
 
# 取数据
myflag = cursor.get(flag)
result = cursor.hget(uid, "familiar_route")

2. 连接Hive

2.1 pyhive

PyHive是Python语言编写的用于操作Hive的简便工具库。

2.1.1  数据查询

from pyhive import hive
conn = hive.Connection(host='localhost', port=10000,
    auth='NOSASL', database='db_name',
    username='zz', password='hive')
cursor = conn.cursor()
print('*' * 20, 'hive已连接')
cursor.execute('select * from XX limit 10')
# df = pd.read_sql(sql, conn)
data = cursor.fetchall()
for result in data:
    print(result)

# conn.commit()
cursor.close()
conn.close()
print('*' * 20, 'hive连接已关闭')
或
with hive.connect(host, port, ...).cursor() as cursor:
    cursor.execute(query_sql)

1.fetchall() 一次读取所有数据,返回一个list对象,并且list里每个元素都是一个tuple对象。

2. fetchone()  一次读取一行数据

3.fetchmany(size=n) 一次读取n行数据

备注:PyHive是通过与HiveServer2通讯来进行Hive数据的操作的。类似Beeline原理(使用的是Hive JDBC),所以当PyHive出现连接有问题时,

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值