programing

Mysql/Maridb Python Connector가 테이블에 데이터를 로드하지 않습니다.

itsource 2022. 10. 15. 11:01
반응형

Mysql/Maridb Python Connector가 테이블에 데이터를 로드하지 않습니다.

# Module Imports
import mariadb
import sys
import csv
from pathlib import Path

def connect_to_mariaDB(databse, user, passwd):
    # Connect to MariaDB Platform
    try: conn = mariadb.connect( 
        user=user, 
        password=passwd, 
        host="localhost", 
        port=3306, 
        database=databse 
    ) 
    except mariadb.Error as e: 
        print(f"Error connecting to MariaDB Platform: {e}") 
        sys.exit(1) 
    return conn

def check_if_table_exists_and_overwrite(conn, tableName, database, overwrite):
    cur = conn.cursor() 
    cur.execute(f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{database}';") 
    for(table_name) in cur:
        if table_name[0] == tableName:
            if overwrite == "YES":
                print("table exists - DROP TABLE")
                cur.execute(f"DROP TABLE {tableName}")
                return True        
            else:
                return False
    return True

def import_file_into_db_table_(
filename, database, user, passwd, tableName,
create_table_statement = "", overwrite = False):

    conn = connect_to_mariaDB(database, user, passwd)
    cur = conn.cursor()
    if conn != None:
        print(f"Connection successful to database {database}")
        
        if check_if_table_exists_and_overwrite(conn, tableName, database, overwrite):
            cur.execute(create_table_statement)
            print("table is created")
            
            path = f"{Path().absolute()}\\{filename}".replace("\\","/")
            print(path)
            load_data_statement = f"""LOAD DATA INFILE '{path}' 
                                    INTO TABLE {tableName} 
                                    FIELDS TERMINATED BY ';' 
                                    OPTIONALLY ENCLOSED BY '\"' 
                                    LINES TERMINATED BY '\\n' 
                                    IGNORE 1 LINES
                                    """
            print(load_data_statement)
            cur.execute(load_data_statement)
            print("load data into table - successful")
            
        else:
            print("table exists - no permission to overwrite")

    cur.execute("SELECT * FROM student_mat;")
    for da in cur: 
        print(da)
        

# variables
filename = "student-mat.csv"
database = "dbs2021"
tableName = "student_mat"

# load the create_table_statement
create_table_statement = ""
path = f"{Path().absolute()}\\create_table_statement.txt"
with open(path, newline='') as file:
    spamreader = csv.reader(file, delimiter='\n', quotechar='|')

    for row in spamreader:
        create_table_statement += row[0]
        
parameters_length = len(sys.argv)
if parameters_length == 3:
    user, passwd = sys.argv[1], sys.argv[2]
    import_file_into_db_table_(filename, database, user, passwd, tableName, create_table_statement, "YES")
elif parameters_length == 4:
    user, passwd, overwrite = sys.argv[1], sys.argv[2], sys.argv[3]
    import_file_into_db_table_(filename, database, user, passwd, tableName, create_table_statement, overwrite)
else:
    print("wrong parameters\nTry -user -passwd or additional -overwrite")

코드는 db에 같은 이름의 테이블이 있는지 확인한 후 이를 폐기하고 새 테이블을 생성하여 csv 파일의 데이터를 테이블에 로드합니다.코드를 실행할 때는 모든 것이 동작하고 있는 것처럼 보이지만 mariadb 명령 프롬프트를 실행하면 작성된 테이블이 비어 있습니다.코드의 테이블을 출력할 때는 테이블이 가득 찼습니다.

기본적으로는 MariaDB Connector/Python은 자동 커밋 모드를 사용하지 않습니다.

둘 중 하나의 세트가 필요합니다.autocommit=True접속을 확립할 때 또는 변경을 커밋할 필요가 있는 경우conn.commit().

언급URL : https://stackoverflow.com/questions/67520204/mysql-maridb-python-connector-is-not-loading-data-into-table

반응형