操作MySQL数据库
PyMySQL是在Python3.x版本中用于连接MySQL服务器的一个库,Python2中则使用mysqldb。
#coding=utf-8
import pymysql
#创建连接数据库对象
con=pymysql.connect(host='localhost',user='root',password='hdc@328216',database='my_test2',port=3306)
#创建游标
cur=con.cursor()
sql='''create table t_student(
sid int primary key auto_increment,
sname varchar(255),
sage int,
source float
)'''
try:
#执行建表sql语句
cur.execute(sql)
print('建表成功')
except Exception as e:
print(e)
print('建表失败')
finally:
cur.close()
con.close()
ssh通道连接msyql
import pymysql
from configparser import ConfigParser
import os
import socket
import socks
import time
from sshtunnel import SSHTunnelForwarder
cf=ConfigParser(allow_no_value=True)
current_path=os.path.dirname(__file__)
root_path=os.path.dirname(current_path)
conffile_path=os.path.join(root_path+'/','config/conf.ini')
cf.read(conffile_path)
dbhost=cf.get("dbinfo","dbhost")
dbuser=cf.get("dbinfo","dbuser")
dbpasswd=cf.get("dbinfo","dbpasswd")
dbport=cf.get("dbinfo","dbport")
dbname=cf.get("dbinfo","dbname")
class MysqlUtils:
def __init__(self):
try:
self.server = SSHTunnelForwarder(
("18.183.69.64",22), #ssh通道跳转机的address,端口号
ssh_username="ubuntu", #ssh通道跳转机的用户名
ssh_pkey="C:/Users/chawey/.ssh/id_rsa_53", #私钥路径
remote_bind_address=(dbhost,3306), #mysql服务器的address,端口号
local_bind_address=("127.0.0.1",13306)) #将远程数据库的端口号绑定成本机的某个端口号,这里暂定为13306
self.server.start()
self.conn = pymysql.connect(
host="127.0.0.1",
port=13306,
user=dbuser,
password=dbpasswd,
database=dbname
)
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
# self.con=pymysql.connect(host=dbhost,user=dbuser,password=dbpasswd,port=int(dbport),database=dbname)
# self.cursor=self.con.cursor(cursor=pymysql.cursors.DictCursor)
except Exception as e:
print('数据库连接失败',e)
#查询数据
def select(self,sql):
try:
self.cursor.execute(sql)
result = self.cursor.fetchall()
self.close()
self.server.close() #执行完sql要确定关闭服务
except Exception as e:
print('查询数据失败',e)
return result
if __name__ == '__main__':
sql="select * from user_currency_flow where flow_type=6 and biz_no='CONvZzHGVi' order by id desc;"
result=MysqlUtils().select(sql)
print(result[0].get("quantity"))
或者:
def __init__(self):
try:
self.server = SSHTunnelForwarder(
("18.183.69.64", 22), # ssh通道跳转机的address,端口号
ssh_username="ubuntu", # ssh通道跳转机的用户名
ssh_pkey="C:/Users/chawey/.ssh/id_rsa_53", # 私钥路径
remote_bind_address=(dbhost, 3306)) # mysql服务器的address,端口号
#local_bind_address=("127.0.0.1", 13306)) # 将远程数据库的端口号绑定成本机的某个端口号,这里暂定为13306
self.server.start()
self.conn = pymysql.connect(
host="127.0.0.1",
#port=3306,
port=self.server.local_bind_port, #使用server绑定的端口
user=dbuser,
password=dbpasswd,
database=dbname
)
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)