pymysql的實踐

PyMySQL 是在 Python3.x 版本中用於連接 MySQL 服務器的一個庫,Python2中則使用mysqldb
話不多說,直接上代碼來說明用途

#!/user/bin/env python
#coding=utf-8

from pymysql import connect,cursors
from pymysql.err import OperationalError
import os
import configparser as cparser
from builtins import int
from framework.logger import Logger
import time

'''
========讀取config.ini文件中mysql配置========
'''
base_dir = str(os.path.dirname(os.path.dirname(file)))
file_path = base_dir + "\config\config.ini"

cf = configUtil(file_path)
host = cf.get("sitmysqlconf", "host")
port = cf.get("sitmysqlconf", 'port')
db = cf.get("sitmysqlconf", 'db_name')
user = cf.get("sitmysqlconf", 'user')
password = cf.get("sitmysqlconf", 'password')

logger = Logger(logger="mysqlUtils").getlog()

'''
===========封裝MySQL基本操作=============
'''
class mysqlUtils:

def __init__(self):
    '''
    初始化獲得mysql連接
    '''
    try:
        self.conn = connect(host=host,
                            port=int(port),
                            user=user,
                            password=password,
                            db=db,
                            charset='utf8mb4',
                            cursorclass=cursors.DictCursor
                            )
    except OperationalError as e:
        print (e)

def cursor(self):
    '''
    獲得遊標
    '''
    self.conn.cursor()

def getDict(self,tableName,systemID,ColumnNameKey,ColumnNameValue):
    '''
    公共方法,獲取id的字典
    '''
    with self.conn.cursor() as cursor:
        cursor.execute("select *  from %s WHERE system_id = %s and %s = %s",(tableName,systemID,ColumnNameKey,ColumnNameValue))
    Dict = cursor.fetchone()
    self.conn.commit()
    return Dict

    def AttentionLibraryDelete(self,system_id,merchant_id):
    '''非正常刪除數據,即直接操作數據庫刪除'''
    with self.conn.cursor() as cursor:
        cursor.execute("delete  from tableName where system_id = %s and merchant_id = %s;",(system_id,merchant_id))
    self.conn.commit()

      def addMerchantTOIT(self,merchant_id):
    '''把商家關聯到XXX行業中'''
    #realSQL = "INSERT INTO tableName (system_id, merchant_id, business_id, status, creator_id, create_date, updater_id, update_date) VALUES ('7b6a99f3bce14915863cde5104bdf2c3', %s, '11', 'A', '8', unix_timestamp(now())*1000, '8', unix_timestamp(now())*1000);"  % repr(merchant_id)
    with self.conn.cursor() as cursor:
        cursor.execute("INSERT INTO t_sys_merchant_business (system_id, merchant_id, business_id, status, creator_id, create_date, updater_id, update_date) VALUES ('7b6a99f3bce14915863cde5104bdf2c3', %s, '11', 'A', '8', unix_timestamp(now())*1000, '8', unix_timestamp(now())*1000);",(merchant_id))
    self.conn.commit()
    logger.info('把商家【%s】關聯到xxx成功'%merchant_id)

def close(self):
'''
關閉mysql數據庫
'''
self.conn.close()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章