In the previous article, we introduced a simple Pythonweb program to implement helloworld. in this article, we will combine mysql to implement simple database operations, I hope it will be helpful to everyone. this time I will add a database to my python program, mainly to query data from mysql and display it 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 aService. py that reads 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
Among them, cursor.exe cute () returns the number of rows affected by the execution statement. At first I thought it was the returned result, resulting in a long detour. The actual returned result is cursor. fechone (), which indicates obtaining the first execution result. There is also cursor. fetchall (), which means to get all results. If multiple fields are obtained, the results are of the array type and sorted in the order of the query results.
MySQLdb is a module connecting python to a database. This module does not exist. you need to download and install it to the python directory. MAC installation of this module has a strange requirement that mysql must be installed on the local machine, even if the program actually uses an external database. If the mysqldb installation error is found and the mysql directory cannot be found, you can solve the problem as follows:
In the user's home directory vi. profile
Add export PATH = $ PATH:/user/local/mysql/bin, exit and save
Run the source./. profile command and exit the terminal.
After that, the mysql directory cannot be found when mysqldb is re-installed.
Next, 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()
In this section, an access path/Service/A is created, and the Service corresponding to this path is provided by the hello class. The getA method of aService is called in the get method of this class. A json text is displayed on the page. The procedure is as follows:
Terminal: python hello. py 8080
Browser: localhost: 8080/Service/