import argparse
import pymysql
class MysqlConnect(object):
# 连接数据库
def __init__(self, opt):
try:
self.conn = pymysql.connect(
host=opt.host,
user=opt.username,
password=opt.password,
db=opt.db,
port=opt.port,
charset=opt.charset,
)
except pymysql.Error as e:
print(e)
# 关闭数据库的连接
def close_conn(self):
try:
if self.conn:
# 关闭连接
self.conn.close()
except pymysql.Error as e:
print(e)
# 自定义你的数据库操作方法
def get_data(self):
# 准备sql
sql = "select * from machine"
# 找到cursor
cursor = self.conn.cursor()
# 执行sql
cursor.execute(sql)
# fetchall全部查
data = cursor.fetchall()
# 关闭cursor/连接
cursor.close()
self.close_conn()
return data
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--host', type=str,
default='***********')
parser.add_argument('--port', type=int, default=*****)
parser.add_argument('--username', type=str, default='******')
parser.add_argument('--password', type=str, default='********')
parser.add_argument('--db', type=str, default='*******')
parser.add_argument('--charset', type=str, default='utf8')
opt = parser.parse_args()
mysql_connect = MysqlConnect(opt)
data = mysql_connect.get_data()
print(data)