Use python develop web page which can read and write mysql database

1. Python access mysql database

Firstly we need install mysql python package: MySQLdb

>sudo pip install mysql-python

And we need setup MySQL on your computer.

Here is the example database table:

example table

Here is the code database_op.py :

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb
import time,datetime

class db_op:
	def __init__(self):
		self.database = MySQLdb.connect("localhost", "root", "chunxie", "house", charset='utf8' )
		self.cursor = self.database.cursor()

	def get_table(self,table):
		sql = "SELECT * FROM %s" % (table)
		try:
			# 执行SQL语句
			self.cursor.execute(sql)
			# 获取所有记录列表
			results = self.cursor.fetchall()
			for row in results:
				hid = row[0]
				location= row[1]
				price = row[2]
				time = row[3]
				# 打印结果
				print("id=%d,location=%s,price=%d,time=%s" % (hid, location, price,time ))
		except:
			print "Error: unable to fecth data"
		return results

	def insert_table(self,table,key,val):
		sql = "INSERT INTO %s(%s,%s,%s,%s) VALUES ('%d', '%s', '%d', '%s' )" % \
       				(table,key[0],key[1],key[2],key[3],val[0],val[1],val[2],val[3])
		#print sql
		
		try:
			# 执行sql语句
			self.cursor.execute(sql)
			# 提交到数据库执行
			self.database.commit()
		except:
			# Rollback in case there is any error
			self.database.rollback()
			print("insert fail")

	def db_showdb(self):
		self.cursor.execute('SHOW DATABASES')
		print(self.cursor.fetchall())

	def db_showtable(self):
		try:
			self.cursor.execute('SHOW TABLES')
			print(self.cursor.fetchall())

		except MySQLdb.Error, e:
			print("Mysql Error %d: %s" % (e.args[0], e.args[1]))

	def db_show_tablehead(self,table_name):
		dbinfo=MySQLdb.connect("localhost", "root", "chunxie", "information_schema", charset='utf8' )
		dbinfo_cursor = dbinfo.cursor()
		sql1="use information_schema;"
		sql2="select COLUMN_NAME from columns where table_name='%s'" % (table_name)
		sql3="show columns from test_table"
		print sql2
		try:
			dbinfo_cursor.execute(sql2)
			tablehead = dbinfo_cursor.fetchall()
			print tablehead
			return tablehead
		except:
			print "Error: unable to fecth table head"
		

	def db_close(self):
		self.database.close()


if __name__=="__main__":
	db=db_op()

	#db.db_showdb()
	table_header=db.db_show_tablehead("test_table")
	print table_header[0][0]
	print table_header[1][0]
	print table_header[2][0]
	print table_header[3][0]

	db.get_table("test_table")

	#gettime()
	print datetime.date.today()
	key=("id","location","price","time")
	value=(4,"Hongkong",8000000,datetime.date.today())
	#db.insert_table("test_table",key,value)

	db.get_table("test_table")
	db.db_close()
	

2. web page with database access capability

It's similar to web page which can access excel file.

Here is the code web_form_db.py :

# -*- coding: utf-8 -*-
#!/usr/bin/env python
import web
from web import form
import database_op
import time,datetime

render = web.template.render('templates/',base='base')

urls =	(
	'/database', 'database',
	'/db-add','database_insert'
	)
app = web.application(urls, globals())


class database:
	def GET(self):
		db=database_op.db_op()
		house_list=db.get_table("test_table")
		table_header=db.db_show_tablehead("test_table")
		head_list=[table_header[0][0],table_header[1][0],table_header[2][0],table_header[3][0]]
		return render.db(head_list,house_list,4)

class database_insert:
	db_form=web.form.Form(
                web.form.Textbox('id', web.form.notnull, description='House id'),
		web.form.Textbox('location', web.form.notnull, description='House location'),
		web.form.Textbox('price', web.form.notnull, description='House price')
        )
	def GET(self):
		self.db_form.render()
		return render.formtest(self.db_form)
	def POST(self):
		new_form=self.db_form()
		if not new_form.validates():
			return render.formtest(new_form)
		else:
			db=database_op.db_op()
			db.get_table("test_table")
			new_id = int(new_form['id'].value.encode('utf-8'))
			new_location = new_form['location'].value.encode('utf-8')
			new_price = int(new_form['price'].value.encode('utf-8'))
			new_time = datetime.date.today()
			print new_id
			print new_location
			print new_price
			print new_time
			new_key = ("id","location","price","time")
			new_value = (new_id,new_location,new_price,new_time)
			db.insert_table("test_table",new_key,new_value)
			db.get_table("test_table")
			db.db_close()
			return "database add one record"	

if __name__=="__main__":
    web.internalerror = web.debugerror
    app.run()

We still need template, here is the template db.html which is for class database:

$def with (head,rows,nclm )

<table border="1" align="center">
$for i in range(0,nclm):
	<td>$head[i]</td>

$for row in rows:
    <tr>
    $for i in range(0,nclm):
        <td>$row[i]</td>
    </tr>
</table>

Here is the template formtest.html which is for class database_insert method POST:

$def with (form)

<div align="center">
<form name="main" method="post"> 
$if not form.valid: <p class="error">Try again, AmeriCAN:</p>
$:form.render()
<input type="submit" description="submit data"/>
</form>
<div>

Here is the template base.html for the whole template:

$def with (page)

<html>
<head>
    <title>Special list</title>
</head>
<body>

$:page

</body>
</html>

database_op.py , web_form_db.py and folder templates are in the same folder.

db.html, base.html and formtest.html are in folder templates.

To run it:

>python web_form_db.py

Then open IE and input http://localhost:8080/database

usage

To add data use http://localhost:8080/db-add

usage2

猜你喜欢

转载自blog.csdn.net/alex_mianmian/article/details/84753297
今日推荐