美文网首页
更新hive元数据-python代码

更新hive元数据-python代码

作者: yuppy_zyp | 来源:发表于2017-11-14 19:35 被阅读0次

    因为之前平台部署的hive下的元数据是放在mysql中的,而mysql由设置了为了拉丁文,导致元数据都是乱码的。

    于是开始了更新计划,办法就是用svn中的建表语句,提取出来写到元数据的mysql下,然后在mysql里进行更新(还好建表语句的备注都写得比较详细)

    方案就是:

    1、用python实现文件遍历,找到sql扩展名的文件。

    2、找出对应的数据库,表名,字段名,备注并写出为文件(或者直接通过python写到mysql)

    3、把结果文件写入到hive的元数据库中

    4、在hive的元数据库中进行匹配

    遇到的问题:

    1、python的文件编码问题(解决办法是先获取文件的编码先成参数,然后再以该编码形式打开文件)

    2、安装mysql-python(mac的电脑需要先安装xcode)

    3、python写入到mysql的乱码问题(设置mysql的编码及在python  connect到mysql的时候加上编码)

    附上python代码。另外mac下用python连接mysql的文章在另一篇。

    #!/usr/bin/python

    #-*- coding: utf-8 -*-

    import sys

    import os

    import re

    import chardet

    import codecs

    import MySQLdb

    path="/Users/zhangyupeng/SVN/10_UAT_DEPLOY/SCFS/"

    #connect the database

    db = MySQLdb.connect(host="localhost" , user="root" , passwd="XXXX" , db="test_python" , charset="utf8")

    cursor=db.cursor()

    for i in os.walk(path):

    file= str(i[2]).strip().split(',')

    for j in file:

    if j.lower().find('.sql')>0:

    #take the SVN file path

    #kill the symbol

    j=j.strip().replace('[','').replace(']','').replace('\'','',10).replace('/','')

    path=str(i[0])+'/'+j

    #pass the udf & 10_TEMP & FXDS

    if path.find('10_TEMP')>0:

    continue;

    if path.find('UDF')>0:

    continue

    if path.find('FXDS')>0:

    continue;

    #open the SVN file and take the info

    with open(path,"rb") as f:

    #open the file with code

    data = f.read()

    code=(chardet.detect(data))

    code_p=str(code)[str(code)[:-2].rfind('\'')+1:].replace('\'','').replace('}','').replace(': ','')

    mysql=codecs.open(path, 'rb',code_p)

    #take the infomation

    for line in mysql:

    p1=line.lower().strip().encode('utf-8')

    a3=''

    a4=''

    p=str(p1)

    #kill the comment

    if str(p)[0:2]=='--':

    continue;

    #search the database & table

    if str(p).find('create')>=0  and str(p).find('table')>=0:

    #take the database

    aa1=str(p)[0:str(p).find('.')]

    a1=aa1[aa1.rfind(' ')+1:]

    #take the table

    a2=str(p)[str(p).rfind('.')+1:].replace('(','')

    #search the field & comment

    if str(p).find('comment')>0:

    #take the field

    a3=str(p)[:str(p).find(' ')]

    #take the comment

    a4=str(p)[str(p).rfind('comment',10)+8:].replace(' ','',20).replace('\'','',10).replace(',','',20)

    #kill the null

    if a3=='' or a3==')':

    continue;

    #print a1+','+a2+','+a3+','+a4

    #print 'database:',a1,'|','table:',a2,'|','field:',a3,'|','comment:',a4

    cursor.execute('insert into svn_field_comment_test values("%s", "%s", "%s", "%s")' % \

    (a1,a2,a3,a4))

    db.commit()

    db.close

    相关文章

      网友评论

          本文标题:更新hive元数据-python代码

          本文链接:https://www.haomeiwen.com/subject/yovfvxtx.html