Python远程连接mysql

测试环境:Ubuntu 17.10

首先安装mysql驱动

sudo apt install python-mysql.connector

操作远程数据库

import mysql.connector
from mysql.connector import errorcode

try:
    # 取得数据库连接
    cnx = mysql.connector.connect(user='xxxx',
                                  password='xxxx',
                                  host='xxxx',
                                  port='xxxx',
                                  database='xxxx')
    cursor = cnx.cursor()

    # querying
    query = ("SELECT name,password FROM user WHERE id=1")
    cursor.execute(query)
    for (name,password) in cursor:
        print("name=%d password=%d\n".format(name,password ))
    cursor.close()

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:
    cnx.close()

猜你喜欢

转载自blog.csdn.net/bobcat_kay/article/details/78368833