2016-11-10 1 views
-1

나는 Flask를 통해 mysql 서버에 연결하는 데 문제가있다. server.py, testDB.py, testDB2.py 및 가 초기화Flask에서 Python을 사용하여 MySQL 서버에 연결하는 방법은 무엇입니까?

init.py 수입 testDB.py과 내가 파이썬 server.py을 실행하면 첫째,이 인쇄됩니다

: 나는 4 개 파일이
changes in the database 
* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit) 

내 user_info 테이블에는 user1이 있습니다. init.py 수입 testDB2.py 내가 파이썬 server.py을 실행하면

그러나, 그것은 단지

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

내 user_info 테이블은 사용자 2가 표시되지 않습니다 인쇄 할 수 있습니다.

어떻게이 문제를 해결할 수 있습니까? testDb.py testDB2.py과 차이가 나는

INIT

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이 주석에서 말한 것처럼, 두 번째 경우에는 데이터베이스가 업데이트되지 않는 이유는 함수를 정의했지만 사용하지 않았기 때문입니다. 파이썬의 다른 함수와 마찬가지로, 다른 코드 라인이 액션으로 호출되기를 기다립니다. 파일을 init.py 파일로 가져 오면 두 가지 방법으로 실행할 수 있습니다. 다음 init.py 파일에서 함수를 실행

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

를, 또는 당신은 단지 함수 외부 (즉, 파일의 끝에 testDB()을 추가하여, 거기에서 기능을 testDB2.py을 수정하고 실행할 수 있습니다 :이 같은 init.py 수정할 수 있습니다 , 당연하지).

관련 문제