Print results in MySQL format with Python

前端 未结 5 522
-上瘾入骨i
-上瘾入骨i 2020-12-05 01:21

What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like tha

5条回答
  •  醉酒成梦
    2020-12-05 01:35

    There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names.

    sql = "SELECT * FROM someTable"
    cursor.execute(sql)
    conn.commit()
    results = cursor.fetchall()
    
    widths = []
    columns = []
    tavnit = '|'
    separator = '+' 
    
    for cd in cursor.description:
        widths.append(max(cd[2], len(cd[0])))
        columns.append(cd[0])
    
    for w in widths:
        tavnit += " %-"+"%ss |" % (w,)
        separator += '-'*w + '--+'
    
    print(separator)
    print(tavnit % tuple(columns))
    print(separator)
    for row in results:
        print(tavnit % row)
    print(separator)
    

    This is the output:

    +--------+---------+---------------+------------+------------+
    | ip_log | user_id | type_id       | ip_address | time_stamp |
    +--------+---------+---------------+------------+------------+
    | 227    | 1       | session_login | 10.0.0.2   | 1358760386 |
    | 140    | 1       | session_login | 10.0.0.2   | 1358321825 |
    | 98     | 1       | session_login | 10.0.0.2   | 1358157588 |
    +--------+---------+---------------+------------+------------+
    

    The magic lies in the third column of each cursor.description line (called cd[2] in the code). This column represents the length in characters of the longest value. Thus we size the displayed column as the greater between that and the length of the column header itself (max(cd[2], len(cd[0]))).

提交回复
热议问题