想尝试自己简单写写从数据库捞测试数据 因为测试数据库有 ssh 通道所以 第一次使用了 with as的写法如下,可以正常捞到数据
import MySQLdb
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
('13.112.45.12', 22), # B机器的配置
ssh_pkey=flie,
ssh_username="dj",
remote_bind_address=(flie2, 3306)) as server: # A机器的配置
conn = MySQLdb.connect(host='127.0.0.1', # 此处必须是是127.0.0.1
port=server.local_bind_port,
user='user_app',
passwd='51e4dbe0',
charset='utf8')
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
sql = "select db_member_01.tb_user.uid from db_member_01.tb_user where uid like '8%' GROUP BY auto_id Asc"
cursor.execute(sql)
results = cursor.fetchall()
经过网上查询过后,发现第一种写法会有些问题 所以换了另一种写法
import MySQLdb
from sshtunnel import SSHTunnelForwarder
server = SSHTunnelForwarder(
ssh_address_or_host=('13.112.45.12', 22), # B机器的配置
ssh_pkey=flie,
ssh_username='dj',
remote_bind_address=(flie2, 3306)
)
server.start()
client = MySQLdb.connect(host='127.0.0.1', # 此处必须是是127.0.0.1
port=server.local_bind_port,
user='user_app',
passwd='51e4dbe0',
charset='utf8')
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
结果就报错了,想问第二种写法问题在哪里
参考资料:http://www.cnblogs.com/luyingfeng/p/6386093.html
http://blog.csdn.net/xw_classmate/article/details/52490354