Python variable passed as hive query

2019-07-23 18:18发布

问题:

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.

回答1:

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


回答2:

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 +";'"



回答3:

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!!!



标签: python hive