Python variable passed as hive query

2019-07-23 18:13发布

I am trying to create a python script that will ask the user for input. This input will be stored in two separate variables and these variables will then used to query hive for information. The code below:

person_database = []
full_name = raw_input('Enter Your Full Name: ')
residence_city = raw_input('Enter City of Interest: ')
def check():    #Define function
`    cmd = "hive -S -e 'SELECT * FROM project.full_score WHERE` person_name=="full_name" AND city=="recidence_city";'"
     person_database = commands.getoutput(cmd)
     print person_database

Now the question is, how to pass the variables to "cmd" in a for that Hive can understand to use what they contain, not the variable name? For example if "full_name" contains "John Smith" and "residence_city" contains "Vancouver" then "john Smith" and "Vancouver" should form part of the query.

标签: python hive
3条回答
SAY GOODBYE
2楼-- · 2019-07-23 18:32

Found a better solution based on Pander's answer:

cmd = "hive -S -e 'SELECT * FROM project.full_score WHERE person_name==\"%s\" AND city==\"%s\";'"%(full_name,residence_city)
     person_database = commands.getoutput(cmd)
     print person_database

The \ \ before each " did the trick, now user can input data without having to worry about quotations.

Thank you guys for your help!!!

查看更多
萌系小妹纸
3楼-- · 2019-07-23 18:51

you simply treat cmd as a string and build the text you want:

.......
cmd = "hive -S -e 'SELECT * FROM project.full_score WHERE`    person_name=="%s" AND city=="%s";'"%(full_name,residence_city)
         person_database = commands.getoutput(cmd)
         print person_database
查看更多
三岁会撩人
4楼-- · 2019-07-23 18:56

You can do it by adding + before and after your variables. This way you treat them as strings and + simply concatenates them. cmd = "hive -S -e 'SELECT * FROM project.full_score WHERE person_name=="+ full_name + " AND city==" + residence_city +";'"

查看更多
登录 后发表回答