import MySQLdb, sys, configparser, time, codecs
from main_config import main_Config

def text_to_mysql(project, category, label):

#    config=configparser.ConfigParser()
#    config.read('main.ini')
#    mysql_id=config['settings']["id"]
#    mysql_pass=config['settings']["pass"]

    mysql_id, mysql_pass, projects, root_path, using_os = main_Config()

    g = codecs.open("encode_temp.txt","r", "utf-8")
    texts=g.readlines()
    g.close()

    g = codecs.open("encode_temp.txt","w", "utf-8")
    g.write("")
    g.close()

    ca_la_te=[]
    for n in texts:
        n=n.replace("\n","")
        a=(category,label,n)
        ca_la_te.append(a)

    text_database(project, mysql_id, mysql_pass, ca_la_te)


def text_database(project, mysql_id, mysql_pass, import_data):
    try:
        conn=MySQLdb.connect(db=project, user=mysql_id, passwd=mysql_pass, charset="utf8mb4")
        cursor=conn.cursor()

        sql="insert into text_table(category_name, label_name, original_sentence) values (%s, %s, %s)"
        cursor.executemany(sql, import_data)

        conn.commit()
        cursor.close()
        conn.close()

        #print("テーブル作成OK")

    except Exception as e:
        print(e)
