niloofar niloofar - 4 months ago 11
Python Question

How to have 2 select query in one function?

I want to have two select query in one function both at the same time.

In shop.html:

{% for each in result %}
{{ each }}<br>
{% endfor %}


{% for each in result2 %}
{{ each }}<br>
{% endfor %}


In app.py:

@app.route('/shop/<data>')
def shop(data):
db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" )

cursor = db.cursor()
cursor2 = db.cursor()


query_string = "SELECT * from users"
query_string2 = "SELECT * from people"


cursor.execute(query_string)
cursor2.execute(query_string2)


result = cursor.fetchall()
result2 = cursor.fetchall()

db.close()


return render_template('shop.html', result=result, result2=result2)


But it doesn't work. It just get and prints the first select query.
How can I fix it?

Answer

You tried to fetch from one of the cursors twice:

result = cursor.fetchall()
result2 = cursor.fetchall()

Note that you called cursor.fetchall() in both cases. You wanted the second result to come from the second cursor:

result = cursor.fetchall()
result2 = cursor2.fetchall()
Comments