How to connect Mysql server via Flask use Python? -
i have trouble connect mysql server via flask. have 4 files: server.py ,testdb.py,testdb2.py , init.py
first , if init.py import testdb.py , run python server.py, print
changes in database * running on http://0.0.0.0:8000/ (press ctrl+c quit) my user_info table have user1.
however ,if init.py import testdb2.py , run python server.py,it print
* running on http://0.0.0.0:8000/ (press ctrl+c quit) my user_info table not appear user2.
how solve problem ? difference between testdb.py , testdb2.py defined function in 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
import mysqldb db = mysqldb.connect(host="127.0.0.1",user="root",passwd="1234",db="testdb") cursor = db.cursor() sql="""insert user_info (user_id, user_email, user_password) values ('user1','00000','000000')""" try: # execute sql command cursor.execute(sql) # commit changes in database print "changes in database" db.commit() except: # rollback in case there error print "there 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 user_info (user_id, user_email, user_password) values ('user2','00000','000000')""" try: # execute sql command cursor.execute(sql) # commit changes in database print "changes in database" db.commit() except: # rollback in case there error print "there error" db.rollback() db.close()
just @dirn said in comment, reason database isn't updated in second case because you've defined function, never made use of it. other function in python, waits line of code call action. when import init.py file, have 2 ways of running it. can modify init.py this:
from flask import flask app = flask(__name__) import testdb2 testdb2.testdb() which runs function init.py file, or can modify testdb2.py , run function there, adding testdb() end of file (outside function, of course).
Comments
Post a Comment