[Turn] Python connect the ramp database ssh

Common database connection

first I would not use the SSH connection, I would like an awkward, that is to establish a database locally, the students develop the online data export, then I import local, then let the front-end test students order (rebate system will automatically call the interface and the data off the disk), and then look for the students to develop the export data sql statement, I then import the updated data locally. After some agonizing normal after such a test, so much for everyone to do after this happens, do not step on me again this pit. The Code, the Code ......

. 1  Import OS
 2  Import pymysql
 . 3  Import the traceback
 . 4  
. 5  # absolute Road King entire project root 
. 6 the baseDir = os.path.dirname (os.path.dirname ( __FILE__ ))
 . 7  # database profile with respect to the relative root Engineering path 
. 8 config_filePath the baseDir + = " \\ \\ db_config.ini public " 
. 9  
10  # open database Connectivity 
. 11 DB = pymysql.connect (Host = ' 127.0.0.1 ' , Port = 3306, = User ' the root ' , the passwd = ' @ 123 mypass ', DB = ' Test ' )
 12 is  # using the cursor () method to create a cursor object Cursor 
13 is Cursor = db.cursor ()
 14  # the cursor.execute ( "the SELECT VERSION ()") 
15  # using either fetchone () method to obtain a single data . 
16  # Data cursor.fetchone = () 
. 17  # Print ( "Database Version:% S" Data%)

See local connection is so simple, so let's see how SSH connection is established


SSH database connection

First, your python to install two packages: sshtunnel and paramiko

import pymysql, paramiko
from sshtunnel import SSHTunnelForwarder
 
with SSHTunnelForwarder(
        ( ' 11.11.11.111 ' , 22), # where the IP address is the SSH host name or IP address that appears in the connection information in 
        ssh_username = " tianchuan " , # here is the operation and maintenance for your user name, not the database user name 
        ssh_pkey = " E: \\ \\ tianchuan_rsa zhuom " , # here is the operation and maintenance of the public key file to your storage address 
        remote_bind_address = ( ' stepping stones domain ' , 3306 )) AS Server:
    conn = pymysql.connect(
        host='127.0.0.1',
        port=server.local_bind_port,
        User = ' youhaodongxi ' ,
        the passwd = ' database password ' ,
        DB = ' youhaodongxi ' )
    cur = conn.cursor()
    cur.execute("show databases")
    print(cur.fetchall())

Well, test your code, results as shown below

 

Guess you like

Origin www.cnblogs.com/yanwuliu/p/11653179.html