python链接mysql的代码

前几天我用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()
 
朋友,记得保存下!下次可能你要用到python操作mysql数据库的时候没准还用的上。如果你用django开发的话,要操作数据库可以看看。 django sqlite数据库配置问题
原创文章请注明转载自老王python,本文地址:http://www.cnpythoner.com/post/149.html
原文地址:https://www.cnblogs.com/wanpython/p/2794287.html