Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337019
  • 博文数量: 148
  • 博客积分: 2745
  • 博客等级: 少校
  • 技术积分: 1704
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-30 14:59
文章分类

全部博文(148)

文章存档

2013年(97)

2012年(7)

2011年(3)

2010年(41)

我的朋友

分类: Python/Ruby

2013-01-31 22:31:34

前几天我用python操作了mysql的数据库,发现非常的有趣,而且python操作mysql的方法非常的简单和快速,所以我把代码分享下大家,希望对大家学习有帮助。
 
import sys
import MySQLdb

reload(sys)
sys.setdefaultencoding('utf-8')

def getdata ():
    try:
        conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', port=3306, charset='utf8')
        try:
            cur = conn.cursor()
            sql = r'select * from person'
            cur.execute(sql)
            allPerson = cur.fetchall()
        finally:
            cur.close()
            conn.close()
    except Exception, e:
        print '数据库错误:', e
        return

    for rec in allPerson:
        print rec[0],rec[1]

if __name__ == '__main__':
    getdata()
 
朋友,记得保存下!下次可能你要用到的时候没准还用的上。如果你用django开发的话,要操作数据库可以看看。

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