2

I'm having a problem and I think that I'm missing something very basic. I'm kind of a noob if it comes to programming but I guess I learn quick. I'm trying to make a Python script that asks for user input and then performs Postgresql SELECT. Then, the outcome of SELECT should be put into another script that uses SSH but I can't wrap my head around that SELECT query. There is a basic example of my code, if you have any tips I would appreciate greatly:

print('Diagnostic tool')
print('')
print('Please insert account ID:')
input()
try:
    conn = psycopg2.connect("dbname='psql' user='user' host='localhost' 
    password='pasword'")
    cur = conn.cursor()
    cur.execute("SELECT * FROM exampletable WHERE acc_id = #userinput ")
    cur.fetchall()
except:
    print ("Could not establish connection to Database")

As shown above- how do I perform a query that uses SELECT WHERE table name is user input (acc_id)?

2 Answers 2

1

you can use format function on a string.

id = input("Please enter your id")
# id should be passed to format. 
query = "SELECT * FROM exampletable WHERE acc_id = {} ".format(id)
try:
   conn = psycopg2.connect("dbname='psql' user='user' host='localhost' 
   password='pasword'")
   cur = conn.cursor()
   cur.execute(query )
   cur.fetchall()
except:
 print ("Could not establish connection to Database")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'll try that!
0

You should pass the input as a parameter to the query. If the input string is saved in userInput you can do:

cur.execute("SELECT * FROM exampletable WHERE acc_id = %s", (userInput,))

Note: for input if your purpose is to take just the input without evaluationg as python code you should use the function raw_input().

2 Comments

Great, I'll try that. Thanks for the answer!
My purpose is to perform query to DB that matches columns based on acc_id provided by user input and then my python script uses that output to fill ssh@xxx (where xxx is value of one column) and then uses command "arp vlanxxx (from column) userIP(from column) to check connectivity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.