1. 程式人生 > >Python遠端連線mysql

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()