python 查询 Mysql 并输出到文本

WBOY
풀어 주다: 2016-06-07 16:36:08
원래의
1572명이 탐색했습니다.

学习Python后写的第二个脚本,逻辑有点乱,等以后在优化! #!/usr/bin/env python'''author:wenminCreated on 2013-4-23'''?import MySQLdb?class MySQLHelper: #配置数据库信息并连接 def __init__(self,host="****",user="****",password="****",port=****

学习Python后写的第二个脚本,逻辑有点乱,等以后在优化!

#!/usr/bin/env python
'''
author:wenmin
Created on 2013-4-23
'''
?
import MySQLdb
?
class MySQLHelper:
    #配置数据库信息并连接
    def __init__(self,host="****",user="****",password="****",port=****,charset="utf8"):
        self.host=host
        self.user=user
        self.password=password
        self.port=port
        self.charset=charset
        try:
            self.conn=MySQLdb.connect(host=self.host,user=self.user,passwd=self.password,port=self.port)
            self.conn.set_character_set(self.charset)
            self.cur=self.conn.cursor()
        except MySQLdb.Error as e:
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
    #取出需要统计的数据库名称
    def db_name(self):
        un_db_name = ['information_schema','cz','ecshop','edutone','gz','mysql','newparent','parent','performance_schema','test','xx','yyhd']
        name = []
        try:
            self.cur.execute('show databases')
            for row in self.cur.fetchall():
                for i in row:
                    if i not in un_db_name:
                        name.append(i)
            return name
        except MySQLdb.Error as e:
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
    #指定查询的数据库名称
    def selectDb(self,db):
        try:
            self.conn.select_db(db)
        except MySQLdb.Error as e:
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
    #查询用户数
    def user_quantity(self):
        try:
            self.cur.execute('select count(distinct phone) from pc_user')
            for row in self.cur.fetchall():
                return row[0]
        except MySQLdb.Error as e:
            print("Mysql Error:%s\n" %(e))
    #查询用户详细信息
    def user_details(self,db):
        try:
            self.cur.execute('select a.phone,a.parents_name,a.student_name,a.type,c.grade_name,b.class_name,a.sex,"'+str(db)+'"from pc_user a,pc_class b,pc_grade c where a.class_id=b.id and a.grade_id=c.id group by a.phone')
            #for row in self.cur.fetchall():
            #   return row
            s = self.cur.fetchall()
            return s
        except MySQLdb.Error as e:
            print("Mysql Error:%s\n" %(e))
    #查询议案数
    def monion_quantity(self):
        try:
            self.cur.execute('select count(distinct id) from pc_motions')
            for row in self.cur.fetchall():
                return row[0]
        except MySQLdb.Error as e:
            print("Mysql Error:%s\n" %(e))
    #查询有效议案
    def monion_details(self):
        try:
            self.cur.execute('select `motion_id`,count(*) from pc_motion_voterec group by motion_id having count(*)>5')
           # for row in self.cur.fetchall():
           #     return row
            s = self.cur.fetchall()
            return s
        except MySQLdb.Error as e:
            print("Mysql Error:%s\n" %(e))
?
    def close(self):
        self.cur.close()
        self.conn.close()
?
if __name__ == '__main__':
    school_db_name = MySQLHelper()
    school = school_db_name.db_name()
    for i in school:
        file = open('jwh/%s' % i,'w')
        file.write("================================================\n")
        d_name = str(i)
        i = MySQLHelper()
        i.selectDb(d_name)
        file.write("user_quantity:"+str(i.user_quantity())+"\n")
        file.write("================================================\n")
        s=i.user_details(d_name)
        for p in s:
            for m in p:
                file.write(str(m)+'  ')
            file.write("\n")
        file.write("================================================\n")
        file.write("monion_quantity:"+str(i.monion_quantity())+"\n")
        file.write("================================================\n")
        l=i.monion_details()
        for p in l:
            for s in p:
                file.write(str(s)+"  ")
            file.write("\n")
        i.close()
        file.close()
    school_db_name.close()
로그인 후 복사
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿