MySQLdb是一个Python的Mysql数据库接口,Python通过它来实现对Mysql数据库的操作,可以在这里找到它。
实例代码:
- # coding: utf-8
- from mod_python import apache
- import os, sys, string
- import MySQLdb
- class Mysql:
- def __init__(self,server='localhost',username='root',password='',database='test',char='utf-8'):
- try:
- self.conn =MySQLdb.connect(host=server,user=username,passwd=password,db=database)
- self.cursor = self.conn.cursor()
- except Exception, e:
- self.__log(e)
- sys.exit()
- def __del__(self):
- self.conn.close()
- self.cursor.close()
- def excute(self,sql):
- try:
- self.cursor.execute(sql)
- except Exception, e:
- self.__log(e)
- def executes(self,sql,val):
- return false
- def getAll (self,sql):
- self.cursor.execute(sql)
- return self.cursor.fetchall()
- def __log(self,e):
- print e
- def handler(req):
- req.content_type = 'text/html'
- sql = "create table if not exists user(username varchar(128) primary key, password varchar(128) NOT NULL,age int(4))"
- mysql = Mysql()
- sql = "insert into user(username,password,age) values ('%s','%s',%d)"
- mysql.excute(sql % ("万新","123",26))
- mysql.excute(sql % ("吴明","123",23))
- rs = mysql.getAll('select * from user')
- if rs:
- req.write("
") ")姓名 密码 年龄 - for res in rs:
- req.write("
")"+res[0]+" ")- req.write("
"+res[1]+" ")- req.write("
"+str(res[2])+" - req.write("
- return apache.OK
显示结果: