欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python基于ssh遠(yuǎn)程連接Mysql數(shù)據(jù)庫操作

 更新時(shí)間:2022年06月23日 11:50:34   作者:數(shù)據(jù)人阿多  
這篇文章主要為大家介紹了Python基于ssh遠(yuǎn)程連接Mysql數(shù)據(jù)庫操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

背景

如果需要訪問遠(yuǎn)程服務(wù)器的Mysql數(shù)據(jù)庫,但是該Mysql數(shù)據(jù)庫為了安全期間,安全措施設(shè)置為只允許本地連接(也就是你需要登錄到該臺服務(wù)器才能使用),其他遠(yuǎn)程連接是不可以直接訪問,并且相應(yīng)的端口也做了修改,那么就需要基于ssh來連接該數(shù)據(jù)庫。這種方式連接數(shù)據(jù)庫與Navicat里面界面化基于ssh連接一樣。

Navicat

連接數(shù)據(jù)庫

安裝支持庫

  • 如果要連接Mysql,首先需要安裝pymysql
pip install pymysql
  • 安裝基于ssh的庫sshtunnel
pip install sshtunnel    #當(dāng)前最新 0.3.1版

建議安裝最新的sshtunnel庫,舊版本庫有一些bug

連接Mysql

基于ssh連接Mysql可以查看sshtunnel的文檔,里面有一些案例

with SSHTunnelForwarder(
        ('192.168.1.1', 2222),
        ssh_password='123456',
        ssh_username='root',
        remote_bind_address=('127.0.0.1', 3306)) as server:
    print('SSH連接成功')
    conn = pymysql.connect(host='127.0.0.1',
                           port=server.local_bind_port,
                           user='root',
                           database='data',
                           charset='utf8')
    print('mysql數(shù)據(jù)庫連接成功')
    cursor = conn.cursor()
    ...  #獲取數(shù)據(jù)操作,此處省略
    cursor.close()
    conn.close()

自定義查詢函數(shù)

可以對上面的連接進(jìn)行封裝為一個(gè)函數(shù),方便其他地方使用

def mysql_ssh(sql,args=None):
    with SSHTunnelForwarder(
            ('192.168.1.1', 2222),
            ssh_password='123456',
            ssh_username='root',
            remote_bind_address=('127.0.0.1', 3306)) as server:
        print('SSH連接成功')
        conn = pymysql.connect(host='127.0.0.1',
                               port=server.local_bind_port,
                               user='root',
                               database='data',
                               charset='utf8')
        print('mysql數(shù)據(jù)庫連接成功')
        cursor = conn.cursor()
        print('游標(biāo)獲取成功')
        try:
            print(f'執(zhí)行查詢語句:{sql}  參數(shù):{args}')
            cursor.execute(sql,args)
            print('數(shù)據(jù)查詢成功')
            conn.commit()
            print('事務(wù)提交成功')
            datas = cursor.fetchall()
            success = True
        except:
            print('數(shù)據(jù)查詢失敗')
            datas = None
            success = False
        print('正在關(guān)閉數(shù)據(jù)庫連接')
        cursor.close()
        conn.close()
    return datas, success

注意點(diǎn):

  • 在使用數(shù)據(jù)庫時(shí),conn.commit()、cursor.close()、conn.close()這些一定要規(guī)范使用,防止不必要的bug
  • 傳入?yún)?shù)時(shí)建議用這種方式cursor.execute(sql,args),防止sql注入的風(fēng)險(xiǎn)

相關(guān)參考:

Python加載txt數(shù)據(jù)亂碼問題升級版解決方法

Python文件打包成exe可執(zhí)行程序

以上就是Python基于ssh遠(yuǎn)程連接Mysql數(shù)據(jù)庫操作的詳細(xì)內(nèi)容,更多關(guān)于Python ssh遠(yuǎn)程連接Mysql的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論