mysql_db.py 2.98 KB
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import configparser
import pymysql.cursors
import os

from . import config_data as Data
#
# base_dir = str(os.path.dirname(os.path.dirname(__file__)))
# config_dir = base_dir.replace('\\', '/')
# config_path = config_dir + '/config.ini'
#
# cp = configparser.ConfigParser()
# cp.read(config_path)
# DB_host = cp.get('mysqlconf', 'host')
# DB_port = cp.get('mysqlconf', 'port')
# DB_username = cp.get('mysqlconf', 'user')
# DB_password = cp.get('mysqlconf', 'password')
# DB_dbName = cp.get('mysqlconf', 'db_name')


class DB:

    def __init__ (self):
        try:
            self.connection = pymysql.connect(host=Data.DB_HOST,
                                         port=Data.DB_PORT,
                                         user=Data.DB_USERNAME,
                                         password=Data.DB_PASSWORD,
                                         charset='utf8mb4',
                                         cursorclass=pymysql.cursors.DictCursor
                                         )
        except pymysql.err.OperationalError as e:
            print ("MySql error %d: %s" % (e.args[0], e.args[1]))

    def select(self, sql):
        with self.connection.cursor() as cursor:
            if cursor.execute(sql):
                return cursor.fetchall()
            else:
                return None

    def select_(self, tabel_name, where_data_equal, where_data_unequal = None ):
        sql_where = ' and '.join("{} = '{}' ".format(key, value) for (key, value) in where_data_equal.items())
        if where_data_unequal:
            sql_where = sql_where + ' and ' + where_data_unequal
        sql = 'select count(1) from  ' + tabel_name + ' where ' + sql_where
        with self.connection.cursor() as cursor:
            cursor.execute(sql)
            result = cursor.fetchone()
            return result['count(1)']


    def insert(self, table_name, table_data):
        for key in table_data:
            table_data[key] = " '" + str(table_data[key]) + "'"
        key = ','.join(table_data.keys())
        value = ','.join(table_data.values())
        real_sql = 'INSERT INTO ' + table_name + " (" + key + " ) VALUES ( "\
                    + value + " )"
        with self.connection.cursor() as cursor:
            cursor.execute(real_sql)
        self.connection.commit()

    def update(self, table_name, set_data, where_data):
        sql_set = ','.join("{}='{}'".format(key, value) for (key, value) in set_data.items())
        sql_where = ' and '.join("{}='{}'".format(key, value) for (key, value) in where_data.items())
        print(sql_set, sql_where)
        real_sql = "UPDATE " + table_name + " SET " + sql_set + " WHERE " + sql_where

        with self.connection.cursor() as cursor:
            cursor.execute(real_sql)
        self.connection.commit()


    def update_(self, sql):
        with self.connection.cursor() as cursor:
            cursor.execute(sql)
        self.connection.commit()


    def close(self):
        self.connection.close()