Python 链接Mysql数据库

参考链接:https://pypi.python.org/pypi/PyMySQL#downloads

import pymysql.cursors,xml.dom.minidom
# Connect to the database
connection = pymysql.connect(host='192.168.75.134',
                             user='sdo',
                             password='51..sdo',
                             db='sdo_config',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
def checkGameTask(connection):
    game_task_xml = open("gameTask_Check.xml",'w',encoding='utf-8')
    impl = xml.dom.minidom.getDOMImplementation()
    dom = impl.createDocument(None, 'RECORDS', None)
    root = dom.documentElement
    try:
        with connection.cursor() as cursor:
            sql = "SELECT `EventID`,`ScoreType`,`ScoreValue`,`TaskGate`,`TaskID`,`TaskState`,`TaskType`,`condExpr` FROM `gameTask`"
            cursor.execute(sql)
            results = cursor.fetchall()
            for row in results:
                cfg = dom.createElement('RECORD')
                cfg.setAttribute('TaskID','%s'%int(row.get('TaskID')))
                cfg.setAttribute('TaskType','%s'%int(row.get('TaskType')))
                cfg.setAttribute('EventID','%s'%int(row.get('EventID')))
                cfg.setAttribute('condExpr','%s'%int(row.get('condExpr')))
                cfg.setAttribute('TaskState','%s'%int(row.get('TaskState')))
                cfg.setAttribute('TaskGate','%s'%int(row.get('TaskGate')))
                cfg.setAttribute('ScoreType','%s'%int(row.get('ScoreType')))
                cfg.setAttribute('ScoreValue','%s'%int(row.get('ScoreValue')))
                root.appendChild(cfg)
            dom.writexml(game_task_xml, addindent='    ', newl='\n')
    finally:
        connection.close()

checkGameTask(connection)

 

posted @ 2016-08-15 15:02  你好阿汤哥  Views(247)  Comments(0Edit  收藏  举报