簡體   English   中英

通過組合 2 個表寫入 sqlite 3 數據庫

[英]Writing to sqlite 3 databse by combining 2 tables

我有兩張桌子,顧客和課程。 我想用正確的客戶 ID 將日期和時間寫入我的課程表的正確行中。 我想使用客戶登錄時輸入的用戶名從客戶表中獲取客戶 ID,然后使用該客戶 ID 將日期和時間插入正確的位置。 這是我的代碼:

with sqlite3.connect('sqlite.db') as db:
            c = db.cursor()
    custid = c.execute('SELECT customerid FROM customers WHERE customerusernm = @username2')
    print(custid)
    c.execute('INSERT INTO lessons(lessondt,lessontm) VALUES (dt,tm) WHERE custid = customerid')
    connect.commit()
    connect.close()

我在使用 select 語句時收到此錯誤:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.

我該如何解決這個問題,是否有更好的方法來做到這一點?

您必須提供一個元組,該元組的值應該綁定在您編寫“@username2”的位置。 請嘗試以下操作:

with sqlite3.connect('sqlite.db') as db:
            c = db.cursor()
    # set the variable to the username you want to compare to
    username = 'some username'
    custid = c.execute('SELECT customerid FROM customers WHERE customerusernm = @username2', (username,))
    print(custid)
    c.execute('INSERT INTO lessons(lessondt,lessontm) VALUES (dt,tm) WHERE custid = customerid')
    connect.commit()
    connect.close()

根據您檢索用戶名的方式,您可以使用getpass模塊:

import getpass    

username = getpass.getuser()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM