首页 数据库 mysql教程 python 查询 Mysql 并输出到文本

python 查询 Mysql 并输出到文本

Jun 07, 2016 pm 04:36 PM
mysql python 学习 文本 查询 输出

学习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()
登录后复制
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

在PHP和Python之间进行选择:指南 在PHP和Python之间进行选择:指南 Apr 18, 2025 am 12:24 AM

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

MySQL的角色:Web应用程序中的数据库 MySQL的角色:Web应用程序中的数据库 Apr 17, 2025 am 12:23 AM

MySQL在Web应用中的主要作用是存储和管理数据。1.MySQL高效处理用户信息、产品目录和交易记录等数据。2.通过SQL查询,开发者能从数据库提取信息生成动态内容。3.MySQL基于客户端-服务器模型工作,确保查询速度可接受。

PHP和Python:深入了解他们的历史 PHP和Python:深入了解他们的历史 Apr 18, 2025 am 12:25 AM

PHP起源于1994年,由RasmusLerdorf开发,最初用于跟踪网站访问者,逐渐演变为服务器端脚本语言,广泛应用于网页开发。Python由GuidovanRossum于1980年代末开发,1991年首次发布,强调代码可读性和简洁性,适用于科学计算、数据分析等领域。

notepad 怎么运行python notepad 怎么运行python Apr 16, 2025 pm 07:33 PM

在 Notepad 中运行 Python 代码需要安装 Python 可执行文件和 NppExec 插件。安装 Python 并为其添加 PATH 后,在 NppExec 插件中配置命令为“python”、参数为“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通过快捷键“F6”运行 Python 代码。

Python:自动化,脚本和任务管理 Python:自动化,脚本和任务管理 Apr 16, 2025 am 12:14 AM

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

Golang vs. Python:并发和多线程 Golang vs. Python:并发和多线程 Apr 17, 2025 am 12:20 AM

Golang更适合高并发任务,而Python在灵活性上更有优势。1.Golang通过goroutine和channel高效处理并发。2.Python依赖threading和asyncio,受GIL影响,但提供多种并发方式。选择应基于具体需求。

See all articles