I am new to Python. While this is similar to a previous question I asked - I am now looking for some information specifically on syntax. I set up the following test below to attempt to take a number from a query and feed it into another query. The specific problem I am having is with the line "cursor.execute("SELECT text FROM feed WHERE id=" + str(rows))". I receive syntax errors.
When I print the query in Python, the record shows up in parenthesis with a comma after it, which I believe is what is causing the error (as these characters are unexpected for the next query).
Being new to this, my question is, should I use "Replace" to strip the result down to a number with no other characters, or, is there something different I should be doing. What is the proper way to pass this number in?
import psycopg2
try:
connect_str = "dbname='mydatabase' user='myuser' host='localhost' " + \
"password='mypassword'"
# establish a connection
conn = psycopg2.connect(connect_str)
# cursor to execute queries
cursor = conn.cursor()
# run am initial SELECT statement
cursor.execute("SELECT result FROM mytable WHERE id=1")
# assign fetched data to a variable named rows
rows = cursor.fetchone()
# for testing purposes, print the variable
print(rows)
# for testing purposes, use it in a sentence
print("the following is your next row",rows)
# feed the result stored in rows into another query
cursor.execute("SELECT result FROM mytable WHERE id=" + str(rows))
morerows = cursor.fetchone()
except Exception as e:
print("cant connect")
print(e)