pythonScript与mysql SP的漂亮输出

os8fio9y  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(161)

我真的希望有人能在这里帮我一点忙,在我发疯之前。我试着从一个pythonscript得到一些漂亮的输出,但是失败了。
这是我的剧本

#!/usr/bin/python3

import getpass
import MySQLdb
DATUM           = sys.argv[1]
def sp_res():
    db = MySQLdb.connect(user='root',passwd=pw,host="127.0.0.1",db="pdi_db")
    cursor = db.cursor()
    res = cursor.callproc('sp_stats', [DATUM])
    results = cursor.fetchall()
    print(results)
    cursor.close()
    db.commit()
    db.close()
pw = getpass.getpass()  
sp_res()

=============================================================

输出为:

Some stats
[(datetime.date(2023, 3, 13), Decimal('2215'), Decimal('5'), Decimal('32773'), Decimal('73'), Decimal('2634'), Decimal('1756'), Decimal('1260'), Decimal('1739'), Decimal('393'), Decimal('1896'), Decimal('0'), 44666)]
MySQL connection is closed

我想去掉dataType和(),它应该看起来像(来自bash):

mysql -u root -p -sN pdi_db -e " call sp_conn('2023-03-13');"
Enter password: 
2023-03-13  2215    5   32773   73  2634    1756    1260    1739    393 1896    0   44666

逗号或制表符可用作分隔符

程序如下所示:

CREATE DEFINER=`root`@`localhost` PROCEDURE `pdi_db`.`sp_stats`(IN DATUM date)
BEGIN
-- Count number of days when using an older file than curdate   
  declare NUM_DAYS INT DEFAULT 0;
  SELECT DATEDIFF(curdate(),DATUM)
  into NUM_DAYS;
-- Here we start counting number of VIN per day
WITH  
v_data AS 
  ( select report_date ,datediff((curdate() - interval NUM_DAYS day),tem_update) as delta
    from conn_stats_1 cs
    where report_date = DATUM
          AND pdi_date IS NOT NULL
          -- AND tem_update IS NULL
  ) 
SELECT distinct
       report_date,
       sum(CASE WHEN delta IS NULL THEN 1 ELSE 0 END) OVER () AS never,
       round(sum(CASE WHEN delta IS NULL THEN 1 ELSE 0 END) OVER () * 100 / count(*) OVER ()) AS '%',
       sum(CASE WHEN delta >= 0 AND delta <= 7 THEN 1 ELSE 0 END) OVER () AS 0to7days,
       round(sum(CASE WHEN delta >= 0 AND delta <= 7 THEN 1 ELSE 0 END) OVER () * 100 / count(*) OVER ()) AS '%',
       sum(CASE WHEN delta >7  AND delta <=14 THEN 1 ELSE 0 END) OVER () AS 8to14_days, 
       sum(CASE WHEN delta >14 AND delta <=21 THEN 1 ELSE 0 END) OVER () AS 15to21_day, 
       sum(CASE WHEN delta >21 AND delta <=28 THEN 1 ELSE 0 END) OVER () AS 22to28_day,
       sum(CASE WHEN delta >28 AND delta <=50 THEN 1 ELSE 0 END) OVER () AS 29to50_day,
       sum(CASE WHEN delta >50 AND delta <=60 THEN 1 ELSE 0 END) OVER () AS 51to60_day,
       sum(CASE WHEN delta >60 THEN 1 ELSE 0 END) OVER () AS 60_or_more,
       sum(CASE WHEN delta <0  THEN 1 ELSE 0 END) OVER () AS other,
       count(*) over() as Total
FROM v_data;
-- select NUM_DAYS;
END

希望有人能,如果不能给予我一个解决办法,给我指出正确的方向。

carvr3hs

carvr3hs1#

我设法获得json作为输出。

...
cursor = connection.cursor(dictionary=True)
cursor.execute("call sp_stats('2023-03-13')")
result = cursor.fetchall()
UT = ({json.dumps(result, indent=2, sort_keys=False, default=str)})
for i in UT:
    print(i)
...

相关问题