python獲得mysql連接的最佳使用示例

安裝方法 pip install mysql-connector

#! /usr/env python
# coding: utf-8

import mysql.connector
from mysql.connector import errorcode

docker_mysql = {
    'user': 'xxx',
    'password': 'xxx',
    'host': 'xx.xx.xx.xx',
    'port': 3306,
    'database': 'yyy'
}


def get_mysql_info(sql):
    cnx = cur = None
    try:
        cnx = mysql.connector.connect(**docker_mysql)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print('Something is wrong with your user name or password')
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)
    else:
        cur = cnx.cursor()
        cur.execute(sql)
        for row in cur.fetchall():
            print(row)
    finally:
        if cur:
            cur.close()
        if cnx:
            cnx.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章