zoukankan      html  css  js  c++  java
  • 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()
    
  • 相关阅读:
    CF359B Permutation
    CF859C Pie Rules
    Contest 156
    Contest 155
    Range Module
    python-环境
    Git 使用
    Contest 154
    生命是一种长期而持续的累积过程
    Contest 153
  • 原文地址:https://www.cnblogs.com/sincoolvip/p/8491810.html
Copyright © 2011-2022 走看看