如何在没有硬编码的情况下将数据插入特定行

时间:2017-05-01 15:06:22

标签: python python-3.x sqlite

此代码的目的是实现以下目标:

- 输入用户名

- 检查DB上是否存在

- 如果没有创建新用户

- 添加货币&平衡到新用户行

问题在于我的insert语句。我不确定如何使用定义的变量插入数据时使用WHERE条件。欢迎帮助!

错误消息:TypeError:函数最多需要2个参数(给定4个)

def add_user():strong text
  print("enter new username")
  UserLogin = str(input())
  c.execute("SELECT username FROM FinanceDBTable")
  enter code here
  for row in c.fetchall():
    print()

#Convers tuple to string without spaces
    UserNameDB = ''.join(row)

    if UserNameDB == UserLogin:
                print('This username already exisits. please try again')
                add_user()
    else:
            print("Please enter your balanace\n")
            userbalance = input()
            print("Please enter currency\n")
            userCurrency = input()
            c.execute("INSERT INTO FinanceDBTable (balance, currency) VALUES (?,?)",
            (userbalance, userCurrency), "WHERE (username) VALUES (?)", (UserLogin))
            conn.commit()

1 个答案:

答案 0 :(得分:0)

一种方法是这样做,也不使用被称为unpythonic的递归,最终也会抛出错误。加上使它变得更加pythonic。 我不确定你是否可以在INSERT语句中使用WHERE,你可以在UPDATE中获取那个想法,但也可以通过另一个给出用户名值来实现你想要达到的目标

def add_user():
    while True:
        username = input("Username: ")
        c.execute("SELECT username FROM FinanceDBTable WHERE username = ?", (username,))
        results = c.fetchall()
        if len(results) < 1:
            # Add user as there is not user with that username.
            user_balance = int(input("Please enter your balance: "))
            user_currency = input("Please enter currency: ")
            c.execute("INSERT INTO FinanceDBTable(username, balance, currency) VALUES (?,?,?)", (username, user_balance, user_currency))
            conn.commit()
            break
        else:
            # User already exists
            print('This username already exists, please try again.')