简体   繁体   中英

Dump info from database

I'm new to Python, but I'm trying to dump certain info from a database. I currently have the following:

import os,MySQLdb

db = MySQLdb.connect(read_default_file="/etc/my.cnf",read_default_group="mysql",db="DbName")

cursor = db.cursor()

sql = "select * from DatasetStatus"

try:
    print '\n Mysql> ' + sql
    cursor.execute(sql)
    results = cursor.fetchall()

    for row in results:
        incache = row[3]
        size = row[5]

    print "%s"% \
         (size)

except:
    print " Error ($s): unable to fetch data."%(sql)

db.close()

I need to access print "%s" , the size of the datasets, but only for those where "%i" is equal to 1 (meaning it is currently cached). Any thoughts on how I might approach this?

If I understand your question correctly, your loop should rather be:

for row in results:
    incache = row[3]
    if incache == 1:
        size = row[5]
        print size

ie with the print inside the loop and guarded by an if (I simplified away the baroque unneeded structure of the print itself, because this simplest-of-all-prints does exactly the same thing as your convoluted one, and Occam's Razor roolz -- but, that's independent from your question:-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM