python sql语句连接数据库

import MySQLdb


class MysqlSearch(object):

    def __init__(self, page=1, page_size=5):
        self.get_conn()
        self.page = page
        self.page_size = page_size
        self.start = (self.page - 1) * self.page_size
        self.end = self.page * self.page_size

    def get_conn(self):
        try:
            self.conn = MySQLdb.connect(
                host='127.0.0.1',
                user='root',
                passwd='******',
                db='news',
                port=3306,
                charset='utf8'
            )
        except MySQLdb.Error as e:
            print(e)

    def close_conn(self):
        try:
            if self.conn:
                self.conn.close()
        except MySQLdb.Error as e:
            print(e)

    def get_one(self):
        sql = 'SELECT * FROM `news` ORDER BY `create_time` DESC;'
        cursor = self.conn.cursor()
        cursor.execute(sql)
        # 查询数据总数
        print(cursor.rowcount)
        print(cursor.description)
        # w = cursor.fetchall()
        rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone()))
        print(rest)
        print(rest['title'])
        cursor.close()
        self.close_conn()
        return rest

    def get_more(self):
        sql = 'SELECT * FROM `news` ORDER BY `create_time` DESC ;'
        cursor = self.conn.cursor()
        cursor.execute(sql)
        # 查询数据总数
        print(cursor.rowcount)
        print(cursor.description)
        rest = [dict(zip([k[0] for k in cursor.description], row)) for row in cursor.fetchall()]
        print(rest)
        cursor.close()
        self.close_conn()
        return rest

    def get_more_page(self):
        sql = 'SELECT * FROM `news` ORDER BY `create_time` DESC LIMIT %s, %s;' % (self.start, self.end)
        print(sql)
        cursor = self.conn.cursor()
        cursor.execute(sql)
        # 查询数据总数
        print(cursor.rowcount)
        print(cursor.description)
        rest = [dict(zip([k[0] for k in cursor.description], row)) for row in cursor.fetchall()]
        print(rest)
        cursor.close()
        self.close_conn()
        return rest

def main():
    # 参数 第一页 每页一条数据
    obj = MysqlSearch(1, 1)
    # rest=obj.get_more()
    # rest=obj.get_one()
    rest=obj.get_more_page()
    print("*"*12)
    print(rest)

if __name__ == "__main__":
    main()

猜你喜欢

转载自blog.csdn.net/weixin_40744265/article/details/88533121