• python一天一题(2)


    python查询mysql数据库

    import pymysql
    host = '192.168.74.5'
    user = 'root'
    passwd ='root'
    port = 3310
    db = 'dingding'  #数据库名称
    table = 'gl_user'
    
    class SelectMySQL(object):
        def select_data(self,sql):
            result = []
            try:
                self.conn = pymysql.connect(
                    host = host,
                    port = port,
                    user = user,
                    passwd = passwd,
                    db = db,
                    charset='utf8',
                )
                self.cur = self.conn.cursor()
                self.cur.execute(sql)
                alldata = self.cur.fetchall()
                for rec in alldata:
                    print(rec)
                    result.append(rec)
            except Exception as e:
                print('Error msg:',e)
            return result
    
        def closeMysql(self):
            self.cur.close()
            self.conn.close()
    
    if __name__ =='__main__':
        sql = 'select * from gl_user'
        select = SelectMySQL()
        result1 = select.select_data(sql)
        select.closeMysql()
        print(result1)
    
    import pymysql as MySQLdb
    
    hostname = '192.168.74.5'
    user = 'root'
    passwd = 'root'
    port = 3310
    db = 'dingding'
    table = 'gl_user'
    
    class MYSQLCommand(object):
        def __init__(self,host,port,user,passwd,db,table):
            self.host = host
            self.port = port
            self.user = user
            self.passwd = passwd
            self.db = db
            self.table = table
    
        def  connectMysql(self):
            try:
                self.conn = MySQLdb.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset='utf8')
                print(self.conn)
                self.cursor =self.conn.cursor()
            except:
                print('connect mysql error')
    
        def queryMysql(self):
            sql = 'select * from '+self.table
            try:
                self.cursor.execute(sql)
                row = self.cursor.fetchall()
                print(row)
            except:
                print(sql,' execute failed')
    
        def closeMysql(self):
            self.cursor.close()
            self.conn.close()
    
    if __name__=='__main__':
        mysql = MYSQLCommand(hostname,port,user,passwd,db,table)
        mysql.connectMysql()
        mysql.queryMysql()
        mysql.closeMysql()
    
  • 相关阅读:
    linux C/C++编程之库-动态库,静态库创建及使用
    类linux 系统iptables 系统初始化配置
    OS error set
    OpenWrt修改
    OpenWrt backfire trunk源码下载及编译
    OpenWrt compiles
    OpenWrt 学习网址
    nginx编译配置
    cocos2d-x中的坐标系
    SGU 231 Prime Sum 求<=n内有多少对素数(a,b)使得a+b也为素数 规律题
  • 原文地址:https://www.cnblogs.com/sincoolvip/p/8491810.html
Copyright © 2020-2023  润新知