Operation Python3 MySQL database (simplified)

In fact, pymysql very simple, compared to ADO.NET, python operation of the database is simply a fool, but still want to learn more about the package, it can be directly used for subsequent reuse, save time. The code here can be saved as a separate file, use the time after the direct import, instantiate SQLHelper requires a minimum of three parameters, user name, password, and the target database server default is local, can also be modified

import pymysql

class SQLHepler:
    def __init__(self, USER, PASSWORD, DATABASE, HOST='127.0.0.1', CHARSET='utf8'):
        self.HOST = HOST
        self.USER = USER
        self.PASSWORD = PASSWORD
        self.DATABASE = DATABASE
        self.CHARSET = CHARSET

    def get_conn(self):
        conn = pymysql.connect(host=self.HOST, user=self.USER, password=self.PASSWORD, db=self.DATABASE, charset=self.CHARSET)
        cur = conn.cursor()
        return conn, cur

    '''
    功能:单向操作,主要用于(增加,删除,修改)
    参数:安全的sql语句
    '''
    def get_excute_Non_query(self, sql):
        conn, cur = self.get_conn()
        try:
            cur.execute(sql)
            conn.commit()
        except:
            print('查询失败')
            conn.rollback()
        conn.close()

    '''
    功能:查询数据库中数据
    参数:安全的sql语句
    '''
    def get_date_query(self, sql):
        conn, cur = self.get_conn()
        data = None
        try:
            cur.execute(sql)
            data = cur.fetchall()
        except:
            print('查询失败')
        conn.close()
        return data

Original: Big Box  Python3 operations MySQL database (simplified)


Guess you like

Origin www.cnblogs.com/petewell/p/11444850.html