使用Python编程语言连接MySQL数据库代码

时间:2023-01-21 08:27:00

使用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源码,可以关注一下:http://www.iplaypython.com/code/