Reputation: 1031
I'm trying to link html form with python and sql. My requirement is that the user gives an input and that input should be sent to some python function block to execute an sql statement on MS SQL Server and return the results back to the user. Please help in linking the below code : order.html
<html>
<form action="/order" method="POST">
<input type="text" name="month">
<input type="number" name="weekno">
<input type="submit">
</form>
The stock for {{weekno}} is xyz
</html>
order.py :
from flask import Flask,render_template
import sys
app = Flask(__name__)
@app.route('/order', method=['POST'])
def orderdb() :
# using sql server connection statement here
cursor = connection.cursor ()
cursor.execute ("select month,stock from salesdb where weeknumbr=?",weekno)
return render_template('order.html',weekno = weekno)
This is a sample code i'm using here instead of pasting complete code.
Please suggest the syntax to be used so that the query should take the weekno value from the form and execute the query based on weeknumbr condition.
Thanks!!
Upvotes: 1
Views: 8642
Reputation: 1
from flask import request
from flask.ext.mysqldb import MySQL
mysql = MySQL(app)
...
month, weekno = request.form['month'], request.form['weekno']
cursor = connection.cursor ()
cursor.execute ("select month,stock from salesdb where weeknumbr=?",weekno)
cursor.execute()
will return the number of rows modified or retrieved, just like in PHP.
When performing a SELECT query, each row is represented in Python by an array. For the above SELECT query with columns ‘name
’ and ‘phone_number
’, you’ll end up with something like:
['Bob', '9123 4567']
cursor.fetchall()
will return you an array containing each row in your query results. That is, you get an array of arrays. So the above SELECT
query might give you:
[['Bob', '9123 4567'], ['Janet', '8888 8888']]
The easiest thing to do with this is to iterate with something like:
data = cursor.fetchall()
for row in data :
do stuff
You can also use cursor.fetchone()
if you want to retrieve one row at a time. This is handy when you’re doing queries like "SELECT COUNT(*) ...
" which only return a single row.
for simple example to use flask-mysql you could read these:
http://ianhowson.com/a-quick-guide-to-using-mysql-in-python.html
or you can read this for reference http://dev.mysql.com/doc/connector-python/en/connector-python-reference.html
Upvotes: 0
Reputation: 3734
To get value from form, in your case, you should do this:
from Flask import request
...
weekno = int(request.form['weekno'])
I suggest you to read this Flask Quickstart
Upvotes: 1