2016-11-10 67 views
-1

我無法通過Flask連接mysql服務器。 我有4個文件:server.py,testDB.py,testDB2.py和初始化的.py如何通過Flask連接Mysql服務器使用Python?

首先,如果init.py進口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() 
+3

您需要調用'testDB2.py'中的'testDB'函數。 – dirn

回答

0

就像@dirn在註釋中說的那樣,數據庫在第二種情況下沒有更新的原因是因爲你已經定義了一個函數,但從未使用它。就像Python中的任何其他函數一樣,它等待另一行代碼將其付諸實踐。當您將其導入init.py文件時,您有兩種運行方式。您可以修改init.py這樣的:

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

,然後從init.py文件運行的功能,或者您也可以從那裏修改testDB2.py和運行功能,只需通過添加testDB()到該文件的末尾(在函數外, 當然)。