The basic package of pymysql to operate mysql

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pymysql

class Pysql(object):
    def __init__(self):
        self.get_conn()

    def get_conn(self):
        try:
            self.a = 1
            self.conn = pymysql.connect(
                host='',
                port=3306,
                user='root',
                password='',
                charset='utf8',
                database='school'
            )
        except pymysql.Error as e:
            print (s)

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

    def get_one(self):
        """
        :return: Get a piece of data in the database and return the title field of this data
        """
        # prepare sql
        sql = 'SELECT * FROM `news` ORDER BY `create_at` DESC;'
        # get cursor
        cursor = self.conn.cursor()
        # execute sql
        cursor.execute(sql)
        # Get the result dict(zip(['a','b'],(1,2))) ==> {'a': 1, 'b': 2} cursor.fetchone gets this tuple format of the data
        res = dict(zip([x[0] for x in cursor.description],cursor.fetchone()))
        # process result
        print(res['title'])
        # close cursor/connection
        cursor.close()
        self.close_conn()

    def get_more(self,page,page_size):
        """
        :param page: show the current page
        :param page_size: the number of lines displayed per page
        :return: Get the title field of multiple pieces of data in the database
        """
        # prepare sql
        offset = (page - 1) * page_size
        sql = 'SELECT * FROM `news` WHERE `types`=%s ORDER BY `create_at` DESC LIMIT %s,%s;'
        # get cursor
        cursor = self.conn.cursor()
        # execute sql
        cursor.execute(sql,('Tencent',offset,page_size))
        # get the result
        # print(cursor.fetchall())
        res = [dict(zip([x[0] for x in cursor.description],row)) for row in cursor.fetchall()]
        # process result
        for ele in res:
            print(ele['title'])
        # close cursor/connection
        cursor.close()
        self.close_conn()

    def add_one(self):
        try:
            # prepare sql
            sql =  ("INSERT INTO `news`(`title`,`types`,`content`,`image`,`is_valid`) VALUES"
                    "(%s,%s,%s,%s,%s);"
                    )
            # get cursor
            cursor = self.conn.cursor()
            # execute sql
            cursor.execute(sql,('C1','Ali','I am C1','/static/image/c1.img','1'))
            cursor.execute(sql,('C1','Ali','I am C1','/static/image/c1.img','1',1))
            # commit transaction
            self.conn.commit()
        except:
            print('error')
            self.conn.commit() # If the above commit is wrong, only execute the correct one
            # self.conn.rollback() # rollback if there is an error
        # close the connection
        cursor.close()
        self.close_conn()

def main():
    sql = Pysql()
    # sql.get_more(3,2)
    sql.add_one()

if __name__ == '__main__':
    main()


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325570510&siteId=291194637