m_SQL.py 3.9 KB
Newer Older
李明杰's avatar
李明杰 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import pymysql as MySQLdb
from sqlalchemy import create_engine
import pandas as pd
import re


class Schema:
    # 初始化
    # 参数一 数据库名 参数二表名
    def __init__(self, host='', user='', password='', mysqlName='', port=''):
        self.host = host
        self.user = user
        self.password = password
        self.mysqlName = mysqlName
        self.port = port
        # 打开数据库连接
李明杰's avatar
jayling  
李明杰 committed
17
        self.db = MySQLdb.connect(host=host, user=user, password=password, db=mysqlName, charset='utf8')
李明杰's avatar
李明杰 committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.db.cursor()

    def GetField(self, tableName=""):
        sql = 'select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME = "' + tableName + '"'
        self.cursor.execute(sql)

        str_f = self.cursor.fetchall().__str__()
        c = re.sub('[(), ]', '', str_f)
        str_list = c.split("'")
        field_list = list(filter(None, str_list))[1:]
        self.db.commit()
        return field_list

    def setAddField(self, tableName="", field=""):
        field_list = self.GetField(tableName=tableName)
        if field not in field_list:
            sql = 'ALTER TABLE ' + tableName + ' ADD ' + field + ' INT(16) DEFAULT 0 '
            self.cursor.execute(sql)
            self.db.commit()
        # pd.read_sql_query(sql, con=self.engine)

    def dataframeToMysql(self, data, tableName=""):
        engine_address = "mysql+pymysql://" + self.user + ":" + self.password + "@" + self.host + ":" + self.port + "/" + self.mysqlName
        engine = create_engine(engine_address, echo=True)
        data.to_sql(name=tableName, con=engine, if_exists='append')

    # list写入mysql table.listToMysql(['username','password'],["asd","as"])
    # 参数1 字段list 参数2 valueList
    def listToMysql(self, tableName, valueList=[]):
        try:
            field = ""
            value = ""
            for i, j in zip(self.fieldList, valueList):
                field += i + ','
                value += "'" + j + "',"
            sql = "INSERT INTO {} ({}) VALUES ({})".format(tableName, field[:-1], value[:-1])
            self.cursor.execute(sql)
        except Exception as e:
            print(str(e))

    # csv文件写入mysql 参数一 路径 参数二编码
    def csvToMysql(self, path='', encoding=''):
        import csv
        csv_reader = csv.reader(open(path, encoding=encoding))
        for row in csv_reader:
            try:
                self.listToMysql(row)
            except Exception as e:
                print(str(e))

    # xlsx文件写入mysql 参数一 路径 参数二编码
    def xlsxToMysql(self, path=""):
        import xlrd as xlsx
        for length, dataList in xlsx.open_workbook(path):
            try:
                valueList = []
                for elem in dataList:
                    valueList.append(str(elem.value))
                self.listToMysql(valueList)
            except Exception as e:
                print(str(e))

    def getData(self, tableName="", startTime="", endTime=""):
        engine_address = "mysql+pymysql://" + self.user + ":" + self.password + "@" + self.host + ":" + self.port + "/" + self.mysqlName
        engine = create_engine(engine_address, echo=True)
        sql = 'SELECT * FROM ' + tableName + ' WHERE datetime >= "' + startTime + '" and datetime< "' + endTime + '"'
李明杰's avatar
jayling  
李明杰 committed
85
        print (sql)
李明杰's avatar
李明杰 committed
86
        data = pd.read_sql_query(sql, con=engine)
李明杰's avatar
jayling  
李明杰 committed
87
        print ("****%d"%(len(data)))
李明杰's avatar
李明杰 committed
88 89 90
        return data

    def delData(self, tableName, keyWord):
李明杰's avatar
jayling  
李明杰 committed
91 92
        word = '"' + keyWord + '"'
        sql = 'DELETE FROM {tableName} WHERE query={keys}'.format(tableName=tableName, keys=word)
李明杰's avatar
李明杰 committed
93 94 95 96 97 98 99 100 101 102 103 104 105
        self.cursor.execute(sql)
        self.commit()

    # 关闭数据库连接
    def closeConnect(self):
        self.db.close()

    # 提交
    def commit(self):
        self.db.commit()

    def delete(self, tableName):
        self.db.cursor("DELETE * FROM {}".format(tableName))