gpt4 book ai didi

python - Flask Python 应用程序无法创建数据库游标

转载 作者:行者123 更新时间:2023-11-29 19:39:14 25 4
gpt4 key购买 nike

我正在尝试在flask中执行基本查询,并将其输出。在 prod 中,无法创建 mysql 游标。

这是app.py:

#from flask_mysqldb import MySQL
import pymysql.cursors

connection = pymysql.connect(host='localhost', user='myusr', port=3306, password='mypass', db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)


@app.route('/', methods=('GET', 'POST'))
def email():


form = EmailForm()

try:
with connection.cursor() as cursor:
cursor.execute("SELECT post_title, post_name, YEAR(post_date) YEAR, MONTH(post_date) MONTH FROM mydb.wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3")
r = cursor.fetchall()
print(r)
Exception as e:
print(e)
finally:
connection.close()

我的db gui程序对我的数据库用户具有以下访问权限(参见黑线): img

更新:::当我包含上面的 try 行时收到错误:

2017/01/02 09:10:30 [error] 1042#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xxx.xxx.xxx, server: mysite.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "mysite.com"

我测试了这个导入(fromflask_mysqldb import MySQL)在解释器中工作正常,mysql本身也已安装。

我测试了上面的凭据是否可以通过 gui db 程序进行连接

我做错了什么?我正在关注official documentation对于flask和mysql,但现在我正在关注link2

为什么会失败?有人看到什么了吗?

谢谢

最佳答案

请尝试按以下方式更改代码并直接运行文件

from flask_mysqldb import MySQL

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_PORT'] = '3306'
app.config['MYSQL_DB'] = 'mydb'
app.config['MYSQL_USER'] = 'myuser'
app.config['MYSQL_PASSWORD'] = 'mypass'
mysql = MySQL(app)

@app.route('/')
def test():
cur = mysql.connection.cursor()

if __name__ == '__main__':
app.run()

关于python - Flask Python 应用程序无法创建数据库游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41426783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com