import pymysql


class Province():
    def __init__(self):
        self.cnx = cnx
        self.cursor = cursor

    def Insert(self, line_info):
        select_sql = f"SELECT cityName from cityinfo WHERE cityName='{line_info[0]}'"
        cursor.execute(select_sql)
        result = cursor.fetchone()
        if result:
            print('该信息已存在')
            return
        insert_sql = "INSERT INTO cityinfo values (%s,%s,%s,%s,%s)"
        cursor.execute(insert_sql,(line_info[0],line_info[1],line_info[2],line_info[3],line_info[4]))
        cnx.commit()

    def Query(self, parts_text):
        select_sql = "SELECT * FROM cityinfo WHERE introduction like %s "
        search_term = f"%{parts_text}%"
        cursor.execute(select_sql, search_term)

    def Update(self, field, value):
        update_sql = f"UPDATE cityinfo SET '{field}'= %s "
        cursor.execute(update_sql, value)
        cnx.commit()

    def Delete(self, field, value):
        delete_sql = f"DELETE FROM cityinfo WHERE '{field}'= %s"
        cursor.execute(delete_sql, value)
        cnx.commit()

# def create_table():
#     sql = '''
#     CREATE TABLE IF NOT EXISTS cityinfo (
#         id INT AUTO_INCREMENT PRIMARY KEY,
#         cityname VARCHAR(255) NOT NULL,
#         GDP FLOAT,
#         population INT,
#         area FLOAT,
#         introduction VARCHAR(255)
#     )
#     '''
#
#     cursor.execute(sql)
#
#     cnx.commit()
#     cnx.close()

def search_city(dict_info, cityname):
    city_info = dict_info[cityname]
    return city_info

if __name__ == "__main__":
    cnx = pymysql.connect(host='localhost', user='root', password='123456', database='db1',charset='utf8mb4')
    cursor = cnx.cursor()
    Tool = Province()
    dict_info = {}
    try:
        with open('file.txt', 'r') as f:
            info_lists = f.readlines()
            # headers = info_lists[1]
            # for head in headers.split(',')[0]:
            #     dict_info[head] = ''
            # for key in dict_info.items():
            #     create_table()

            for line in info_lists[1:]:
                line_info = line.split(',')
                key = line_info[0]
                # 定义一个字典
                dict_info[key] = {
                    'GDP':line_info[1],
                    'population':line_info[2],
                    'area':line_info[3],
                    'induction':line_info[4]
                }

                Tool.Insert(line_info)
    except:
        print('该文件不存在')
    # 实现省份的快速查询
    cityname = '河北'
    city_info = search_city(dict_info, cityname)



