Python远程连接mysql

来源:互联网 发布:iphone显示无网络连接 编辑:程序博客网 时间:2024/06/05 23:40

测试环境:Ubuntu 17.10

首先安装mysql驱动

sudo apt install python-mysql.connector

操作远程数据库

import mysql.connectorfrom mysql.connector import errorcodetry:    # 取得数据库连接    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()
原创粉丝点击