首先,我理解使用ORM解决方案的价值,稍后将使用SQL-Alchemy。
我已经安装了Flask并使用了flask-mysql。
我不知道如何获取SQL“desc”命令的结果。
以下是我正在使用的代码:
from flask import Flask, render_template, request, redirect, jsonify
import requests
from flaskext.mysql import MySQL
app = Flask(__name__)
@app.route("/")
def main():
return render_template('login.html')
@app.route("/login", methods=['POST'])
def login():
#username = request.form['username'] #not using the form fields yet
#password = request.form['password']
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = '<my user here>'
app.config['MYSQL_DATABASE_PASSWORD'] = '<password here>'
app.config['MYSQL_DATABASE_DB'] = '<database name here>'
app.config['MYSQL_DATABASE_HOST'] = '<database server IP address here>'
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()
#cursor = mysql.connection.cursor() #invalid code, at least for this version of flask-mysql
cursor.execute("desc user;")
result = jsonify(cursor.fetchall())
#row = cursor.fetchone()
return "<!DOCTYPE html><html><body>" + str(result)+ "</body></html>"
if __name__ == "__main__":
app.run()
它似乎是连接到数据库,登录并发送desc命令,因为结果的内容是“响应268字节[200 OK]”(通过在获得响应后查看页面源代码可以看到浏览器)。
有没有办法获得结果(表格描述),而不只是“我运行此命令好吗?”
谢谢。
答案 0 :(得分:0)
我想你想要获得所有记录并按照desc顺序对它们进行排序。你可以试试这个。
from flask_mysqldb import MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] =
app.config['MYSQL_DB'] =
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# initialize mysql
mysql = MySQL(app)
...
@app.route('/posts')
def posts():
cur = mysql.connection.cursor()
result = cur.execute('SELECT * FROM posts ORDER BY postdate DESC ')
posts = cur.fetchall()
if result > 0:
return render_template('posts.html', posts=posts)
else:
message = 'I shouldn't find any post'
return render_template('posts.html', message=message)
cur.close