2016-11-10 69 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()到该文件的末尾(在函数外, 当然)。