ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • DB 파일 생성(python)
    Python 2023. 7. 4. 12:23
    728x90
    반응형

    python3으로 db파일 생성하는 코드를 한 번 남기려한다.

     

    먼저 내가 원하는 db는 Group : Name이다.

    그리고 여러 db를 만들 예정이라 json파일을 다음과 같이 구성했다.

    {
        "auth101":
    	{
            "TeamA": "Alice,Bob,Charile,David,Elon,net1.downloader",
            "TeamB": "Bob,Charlie,Elon,Zoe",
            "TeamC": "Kong,Bob,Zoe,Shan"
    	},
        "auth102":
        {
            "TeamA": "Alice,Bob,Charile,David,Elon",
            "TeamB": "Bob,Charlie,Elon,Zoe",
            "TeamC": "Kong,Bob,Zoe,Shan"
        }
    }

    auth101.db, auth102.db를 만들 예정이다.

    그리고 db파일에서는 TeamA: Alice, TeamA:Bob 등으로 각각을 구성할 예정이다.

     

    python3 코드는 다음과 같다.

    import sqlite3
    import os
    import json
    from os import path
    
    
    with open("configs/fileDBdefault.json",'r') as f:
        config = json.load(f)
    auth_group = []
    fileshare_data = []
    db = []
    for i in (config.keys()):
        auth_group.append(i)
        fileshare_data.append(config[i])
    
    for i in range(len(auth_group)):
        list = []
        for j in (fileshare_data[i].keys()):
            name_list = fileshare_data[i][j].split(',')
            for k in name_list:
                list.append((j,k))
        db.append(list)
    
    for i,j in enumerate(auth_group):
        # if (str(path.exists('auth/{}/filesharing.db'.format(j)))):
        #     os.system('rm auth/databases/{}/filesharing.db'.format(j))
        con = sqlite3.connect('../auth/databases/{}/filesharing.db'.format(j))
        cur = con.cursor()
        # Create table
        cur.execute('''CREATE TABLE FST (owner, name)''')
        # Insert a row of data
        cur.executemany("INSERT INTO FST VALUES (?,?)",db[i])
    
        # Save (commit) the changes
        con.commit()
    
        # We can also close the connection if we are done with it.
        # Just be sure any changes have been committed or they will be lost.
        con.close()
    print("Generating FileSharing databases...")

    마지막 for문을 제외하고는 그냥 전처리 부분이라.. 그렇고 결과는 다음과 같이 나오게된다.

    정상적으로 잘 나온것을 확인할 수 있다.

    위에서 executemany를 사용하면 여러 리스트를 한 번에 넣을 수 있으니 꽤나 좋은 함수이고 꼭 사용하길 바란다.

     

    728x90
    반응형
Designed by Tistory.