我正在尝试编写一个Python程序,它从用户那里获取解析器参数并将其添加到SQLite数据库中的特定列

问题描述 投票:0回答:1

我正在尝试编写一个Python脚本,多个用户将执行该脚本来添加他们的信息。我的项目是从许多用户那里收集尽可能多的数据,并最终查询用户输入的特定人口统计数据。(例如,根据所有用户所在的机构查询数据。)

我有部分代码提示用户输入参数,但是我不知道如何将数据处理到 SQLite 数据库中的特定列中。


import argparse
import sys
import sqlite3

def main():

    # Creating a parser object
    parser = argparse.ArgumentParser(description = "This program will read users Background data into SQLite Table.")
    
    # Adding argument
    parser.add_argument("--EDUCATIONLEVEL", help = "Adds to database EDUCATIONLEVE Column. Where user insert their Education level")
    parser.add_argument("--INSTITUTION", help = "Adds to database INSTITUTION Column. Where user insert their Education Instution")
    parser.add_argument("--FIELD", help = "Adds to database FIELD Column. >> >> Field of study")
    parser.add_argument("--DATE", help = "Adds to database DATE Column. >> >> Date of degree")
    parser.add_argument("--CAREER", help = "Adds to database CAREER Column. >> >> current Career")
    

    # Parse the arguments from standard input
    args= parser.parse_args()

    # Database connection
    conn = sqlite3.connect("Background.db")  
    cur = conn.cursor() 
    
    # create table function 
    def CreateTable():
        cmd =  """CREATE TABLE IF NOT EXISTS BACKGROUND
                (EDUCATIONLEVEL TEXT,
                INSTITUTION TEXT,
                FIELD TEXT,
                DATE INTEGER,
                CAREER TEXT,
                )"""
        cur.execute(cmd)
        conn.commit()
        
    def InsertToTable():
        cmd = """INSERT OR IGNORE INTO BACKGROUND(EDUCATIONLEVEL, INSTITUTION, FIELD, DATE, CAREER) VALUES (?, ?, ?, ?, ?)""", (Education_Level, Institution, Field, Date, Career)
        cur.execute(cmd)
        conn.commit()
        
      
        
    # invoking creation of BACKGROUND Table
    CreateTable()
    
    # if user input is < 1 invoke help
    if len(sys.argv) < 1:
        parser.print_help()
     
# I want to be able to add data to specific column in the db
    for arg in vars (args):
        if arg == None:
            print("No input specified!")
            parser.print_help()
        
        elif arg == "EDUCATIONLEVEL":
           
        elif arg == "INSTITUTION":
        
        elif arg == "FIELD":
        
        elif arg == "DATE":
            
        elif arg == "CAREER":
                   
        else:
            parser.print_help()
    
    # close connection to the database
    conn.commit()
    conn.close()
    
if __name__ == "__main__":
    main() 
    

python sqlite argparse
1个回答
0
投票

使用字符串格式将所有列名称替换为 SQL 字符串。使用

UPDATE
查询来替换这些列。

colnames = ', '.join(f'{col} = ?' for col in vars(args))
values = vars(args).values()
sql = f'UPDATE BACKGROUND SET {colnames}'
cur.execute(sql, values)

这将更新表中的所有行。您可能需要表中的另一列来标识背景适用于哪个用户(例如,用户表的外键)。然后,您需要向查询添加一个

WHERE
子句,以便它只更新该行。

© www.soinside.com 2019 - 2024. All rights reserved.