【问题标题】:How to connect Mysql server via Flask use Python?如何通过 Flask 使用 Python 连接 Mysql 服务器?
【发布时间】:2016-11-10 19:59:01
【问题描述】:

我无法通过 Flask 连接 mysql 服务器。 我有 4 个文件:server.py、testDB.py、testDB2.py 和 init.py

首先,如果 init.py import testDB.py 并且我运行 python server.py,它将打印

changes in the database
 * Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)

我的 user_info 表将有 user1。

但是,如果 init.py 导入 testDB2.py 并且我运行 python server.py,它只会打印

* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)

我的 user_info 表不会出现 user2。

我该如何解决这个问题? testDb.py 和 testDB2.py 的区别是我在 testDB2.py 中定义了一个函数

初始化.py

from flask import Flask
app = Flask(__name__)
import testDB

server.py

from Sw import app
if __name__ == '__main__':
    port = 8000
    host = '0.0.0.0'
    app.run(host = host, port = port)

testDB.py

import MySQLdb
db = MySQLdb.connect(host="127.0.0.1",user="root",passwd="1234",db="testdb")
    cursor = db.cursor()
    sql="""INSERT INTO user_info (user_id, user_email, user_password) VALUES ('user1','00000','000000')"""
    try:
       # Execute the SQL command
        cursor.execute(sql)
       # Commit your changes in the database
        print "changes in the database"
        db.commit()
    except:
       # Rollback in case there is any error
        print "there is any error"
        db.rollback()
    db.close()

testDB2.py

  import MySQLdb
  def testDB():
        db = MySQLdb.connect(host="127.0.0.1",user="root",passwd="1234",db="testdb")
        cursor = db.cursor()
        sql="""INSERT INTO user_info (user_id, user_email, user_password) VALUES ('user2','00000','000000')"""
        try:
           # Execute the SQL command
            cursor.execute(sql)
           # Commit your changes in the database
            print "changes in the database"
            db.commit()
        except:
           # Rollback in case there is any error
            print "there is any error"
            db.rollback()
        db.close()

【问题讨论】:

  • 需要调用testDB2.py中的testDB函数。

标签: python mysql python-2.7 flask


【解决方案1】:

正如@dirn 在评论中所说,在第二种情况下数据库未更新的原因是因为您定义了一个函数,但从未使用它。就像 Python 中的任何其他函数一样,它等待另一行代码调用它。将其导入init.py 文件时,有两种运行方式。你可以像这样修改init.py

from flask import Flask
app = Flask(__name__)
import testDB2
testDB2.testDB()

然后从init.py 文件运行您的函数,或者您可以修改testDB2.py 并从那里运行函数,只需将testDB() 添加到该文件的末尾(当然是在函数之外)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2014-04-05
    • 2021-07-08
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    相关资源
    最近更新 更多