This time to add a database for my Python program, the main implementation is to query the data from MySQL and display on the page.
The first is the MySQL configuration file config.py
Host= "127.0.0.1" user= "root" password= "" charset= "UTF8" database= "service" port=3306
Then the aservice.py that reads the data from the database
Import Mysqldbimport sysimport Configclass aservice (object): def geta (self,id): conn = MySQLdb.connect (host= Config.host,user=config.user,passwd=config.password,port=config.port,db=config.database,charset=config.charset ) result=[] try: cursor = Conn.cursor (); Cursor.execute ("Select Id,code,title from test_a where id= '%d '"% (ID)) result = Cursor.fetchone () except Exception,e: print "System error:", e result = "Error" finally: cursor.close () conn.close () return result
where Cursor.execute () returns the number of rows affected by the execution statement, at first I thought it was the result of the return, leading to a long detour. The true return result is Cursor.fechone (), which represents the first rule that gets the result of the execution. There is also Cursor.fetchall (), which means getting all the results. If more than one field is obtained, the result is an array type, sorted by the field order of the query results.
MySQLdb is a module for Python to connect to a database. This module does not exist, it needs to be downloaded and installed in the Python directory. A strange requirement for Mac to install this module is that MySQL must be installed natively, even if the program is actually using an external database. In the premise of the installation of MySQL, the installation of MYSQLDB error, and reported that the MySQL directory can not find an error, the following methods may be resolved:
In the user's home directory, VI profile
Join Export path= $PATH:/user/local/mysql/bin, Exit and save
Then execute the source./.profile Command and exit the terminal
After that, you should not be able to find the MySQL directory error when reinstalling MySQLdb.
Next is the main program hello.py
Import webimport aserviceimport sys urls = ("/service/a", "Hello") app = Web.application (Urls,globals ()) class Hello: def GET (self): Mservice = Aservice.aservice () result = Mservice.geta (1) JSON = "" JSON + = " {" JSON + = "' id ':" +str (result[0) + "," json + = "' Code ': '" +result[1]+ "'," json + = "' title ': '" +result[2]+ "'" json + = "}" return json;if __name__== "__main__": App.run ()
This section creates an access path/service/a, which corresponds to a service that is provided by the Hello class. The Geta method of Aservice is called in the Get method of this class. Displays a JSON-formatted text on the page. Follow the steps below
Terminal: Python hello.py 8080
Browser: localhost:8080/service/a