`
dylan.wu
  • 浏览: 134169 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

python链接mysql

 
阅读更多

使用python的时间不久,这几天接到一个小需求,本来想着在linux下使用python实现,但一时手头上没有linux环境,加上这个需求的最终版本需要操作excel 2007,一想得了,干脆就在windows下使用吧,由于输入数据放在mysql中,于是就需要从mysql上取一些数据,虽然数据简单,但还是得想办法连上mysql,查了下Google,貌似MySQL-python这套组件不错,前提本人是比较懒的,不想自个去编译各种库,于是就从python官网上下python2.7,从MySQL-python的非官网上下了MySQL-python-1.2.3.win32-py2.7.exe(谁让官网上没编译好的安装文件),并把MySQL-python安装到python2.7的./Lib/sit-packages/下。

写了个简单的测试代码如下

import sys
import MySQLdb

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

    for rec in allPerson:
        print str(rec)

if __name__ == '__main__':
    getdata()
 

MySQLdb用户指南: http://mysql-python.sourceforge.net/MySQLdb.html
MySQLdb文档: http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics