SQL连接
import pymysql
def sql(path):
conn = pymysql.Connect(host='36.104.34.123', user='用户名', passwd='密码', db='库名')
cursor = conn.cursor()
sql = """
SELECT
x.province,
x.city,
count(DISTINCT x.pid_new)
FROM database.table AS x
WHERE x.province IN ("江苏")
group by x.city
"""
try:
result = cursor.execute(sql)
print(result)
rr = cursor.fetchall()
conn.commit()
except Exception as e:
print(e)
conn.rollback()
for row in rr:
with open(path, 'a+') as f:
print(row)
f.writelines(str(row) + '\n')
f.close()
cursor.close()
conn.close()
hive连接
from impala.dbapi import connect
class Hiveclient():
def __init__(self, user, password):
self.user = user
self.conn = connect(host='master1', port=99999, auth_mechanism='GSSAPI', user=user, password=password,
kerberos_service_name='hive')
def query(self):
print("开始取数啦!!!")
with self.conn.cursor() as curs:
qu_sql = """SELECT
province,
city
FROM database.table
limit 10
"""
print(qu_sql)
try:
curs.execute(qu_sql)
rr = curs.fetchall()
print(type(rr), rr)
for i in rr:
with open(path, 'a+', encoding='GB2312') as f:
print(i, type(i))
f.writelines(str(i) + '\n')
print('=============全部完成===============')
except Exception as e:
print(e)
return
def close(self):
self.conn.close()