Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2109193
  • 博文数量: 333
  • 博客积分: 10161
  • 博客等级: 上将
  • 技术积分: 5238
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-19 08:59
文章分类

全部博文(333)

文章存档

2017年(10)

2014年(2)

2013年(57)

2012年(64)

2011年(76)

2010年(84)

2009年(3)

2008年(37)

分类: Python/Ruby

2010-12-29 10:55:33

2009年1月2日

MySQLdb是一个Python的Mysql数据库接口,Python通过它来实现对Mysql数据库的操作,可以在这里找到它。

实例代码:

  1. # coding: utf-8
  2. from mod_python import apache
  3. import ossysstring
  4. import MySQLdb
  5.  
  6. class Mysql:
  7.     def __init__(self,server='localhost',username='root',password='',database='test',char='utf-8'):
  8.         try:
  9.             self.conn =MySQLdb.connect(host=server,user=username,passwd=password,db=database)
  10.             self.cursor = self.conn.cursor()
  11.         except Exceptione:
  12.             self.__log(e)
  13.             sys.exit()
  14.    
  15.     def __del__(self):
  16.         self.conn.close()
  17.         self.cursor.close()
  18.        
  19.     def excute(self,sql):
  20.         try:
  21.             self.cursor.execute(sql)
  22.         except Exceptione:
  23.             self.__log(e)
  24.    
  25.     def executes(self,sql,val):
  26.         return false
  27.  
  28.     def getAll (self,sql):
  29.         self.cursor.execute(sql)
  30.         return self.cursor.fetchall()
  31.        
  32.  
  33.     def __log(self,e):
  34.         print e
  35.  
  36.  
  37. def handler(req):
  38.     req.content_type = 'text/html'
  39.     sql = "create table if not exists user(username varchar(128) primary key, password varchar(128) NOT NULL,age int(4))"
  40.     mysql = Mysql()
  41.     sql = "insert into user(username,password,age) values ('%s','%s',%d)"
  42.     mysql.excute(sql % ("万新","123",26))
  43.     mysql.excute(sql % ("吴明","123",23))
  44.     rs = mysql.getAll('select * from user')
  45.     if rs:
  46.         req.write("")
  47.         for res in rs:
  48.             req.write("
  49. ")
  50.             req.write("
  51. ")
  52.             req.write("
  53. ")
  54.         req.write("
  55. 姓名密码年龄
    "+res[0]+""+res[1]+""+str(res[2])+"
    ")
  56.     return apache.OK

显示结果:
1

阅读(1682) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~