简体   繁体   English

Flask mysql 得到对 SQL 命令的响应(不使用 SQL-Alchemy)

[英]Flask mysql getting response to SQL commands (not using SQL-Alchemy)

First, I understand the value of using ORM solutions, and will use SQL-Alchemy later.首先,我了解使用 ORM 解决方案的价值,稍后将使用 SQL-Alchemy。

I have installed Flask and am using flask-mysql.我已经安装了 Flask 并且正在使用 Flask-mysql。

I do not know how to get the results for a SQL "desc " command.我不知道如何获得 SQL“desc”命令的结果。

Here is the code I'm working with:这是我正在使用的代码:

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()

It appears to be connecting to the database, logging in, and sending the desc command OK because result's contents are "Response 268 bytes [200 OK]" (can see that by looking at the page source code after getting the response in the browser).好像是在连接数据库,登录,发送desc命令OK,因为结果的内容是“Response 268 bytes [200 OK]”(在浏览器中得到响应后查看页面源代码即可看到) .

Is there any way to get the results (table description) and not just an "OK I ran this command"?有没有办法获得结果(表格描述)而不仅仅是“我运行了这个命令”?

Thank you.谢谢你。

I suppose you would like to get all records and sort them in desc order.我想您想获取所有记录并按降序对它们进行排序。 You may try this.你可以试试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM