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()

 

转载于:https://www.cnblogs.com/sincoolvip/p/8491810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值