Python3 -- PySQL -- 將函數封裝在類中


 

------------------ comm_functions.py ------------

import pymysql

class common_functions(object):

  # ---- 需要初始化 __init__ 來連接數據庫,並產生 self.cur 供后面函數應用
def __init__(self):
self.conn = pymysql.connect(
host='192.168.68.189',
port=3307,
user='xxxxx',
passwd='xxxx',
db='xxxx',
)
self.cur = self.conn.cursor()

def execute_sqlscript_fetchall_contents(self, sqlscript):
self.cur.execute(sqlscript)
contents = self.cur.fetchall()
return contents

def execute_sqlscript_fetchall_content(self, sqlscript):
contents = self.execute_sqlscript_fetchall_contents(sqlscript)
for row in contents:
data = row[0]
return data

def calculate_sharecycle(self, open_time, clean_time):
sql_sharecycle = "select count(*) from hd_trading_date where open_day >= left(" + open_time + ", 8) and open_day <= left(" + clean_time + ",8)"
sharecycle = self.execute_sqlscript_fetchall_content(sql_sharecycle)
if open_time[8:12] >= "2100":
sharecycle = sharecycle - 1
if clean_time[3][8:12] >= "2100":
sharecycle = sharecycle + 1


------- gen_report.py ----------
import sys
sys.path.append("./sqldata")
from com_functions import common_functions


def get_data():
sharecycle = common_functions().calculate_sharecycle("20171018143914", "20171018210220")
print("sharecycle: %d" % sharecycle)

if __name__ == "__main__":
get_data()
common_functions().close_sql()





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM