2016-11-10 9 views
-1

Flask経由でmysqlサーバに接続するのに問題があります。 私は4つのファイルがあります。init.py輸入testDB.pyと私はPythonのserver.pyを実行する場合、server.py、testDB.py、testDB2.pyとのinitの.pyFlaskでPythonを使用してMysqlサーバーに接続するには?

まず、それが

を印刷します
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の違いは、私が

INITの.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

testDB2.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がコメントの中で述べたように、2番目のケースでデータベースが更新されない理由は、関数を定義してから使用したことがないためです。 Pythonの他の関数と同じように、別のコード行が実行されるのを待ちます。 init.pyファイルにインポートすると、2つの方法で実行できます。その後、init.pyファイルから関数を実行します

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

を、またはあなただけの関数の外(つまり、ファイルの末尾にtestDB()を追加することで、そこから機能をtestDB2.pyを変更して実行することができます:あなたはこのようinit.py変更することができます、 もちろん)。

関連する問題