简体   繁体   中英

Python sqlite3 INSERT FROM existing table to new table WHERE conditions are met

I have two tables in a database. The layout is the same for both(8 columns). I am trying to copy the rows from the first table to the second table where the column value of first table's row(s) is True. If they already exist, then I'd like to just update 5 of the 8 columns. Below is the 2 Tables structure, followed by the function to populate the "new_listings" Table from a nested list of coin data. So far this works perfectly. However, I'm stuck at following conditions:

  1. If 'Coin' is in " new_listings " but NOT in " trade_schedule " AND 'Trade' is = " True " - Then Insert it into table " trade_schedule ".

  2. If 'Coin' is in " new_listings " AND is in " trade_schedule " AND 'Trade' is = " True " - Then Update :'Price', 'Spend_USDT', 'Not_Buy_Above', 'Trailing_SL' in " trade_schedule ".

  3. If 'Coin' is in " new_listings " AND is in " trade_schedule " AND 'Trade' is = " False " - Then Delete 'Coin' row from " trade_schedule ".

I have been trying to get this to work for 2 days now, the best I was able to do is to copy the Table and then set Delete executes to get rid of rows with "Trade" in the 'Trade' column. All my other attempts return syntax errors. I can have this in the same function or create a separate function, either way would be fine.

My brain is melting o_O, any help is much appreciated.

Sample NCLP :

[['LINA', 1638972000000, '0.044077616', '9:00 December 8, 2021', 'False', 0, 0, 0],
['KLAY', 1638975600000, '1.365161764', '10:00 December 8, 2021', 'True', 0, 0, 0],
['CREDI', 1639062000000, '0.000000000', '10:00 December 9, 2021', 'False', 0, 0, 0]]

Code:

conn = sqlite3.connect('coin_db.db')
c = conn.cursor()
c.execute("""CREATE TABLE if not exists new_listings (          
            Coin text,
            Epoch_Date integer,
            Price real,
            Date_UTC text,
            Trade text,
            Spend_USDT real,
            Not_Buy_Above real,
            Trailing_SL real)""")
c.execute("""CREATE TABLE if not exists trade_schedule (          
            Coin text,
            Epoch_Date integer,
            Price real,
            Date_UTC text,
            Trade text,
            Spend_USDT real,
            Not_Buy_Above real,
            Trailing_SL real)""")
conn.commit()
conn.close()

  
def coin_DB_update():
    NCLP_update() # Run NCLP update function to get current coins as nested list.
    conn = sqlite3.connect('coin_db.db')
    c = conn.cursor()
    for coin in NCLP:
        c.execute("SELECT Coin FROM new_listings WHERE Coin=?", (coin[0],))
        c_result1 = c.fetchone()
        if c_result1:
            c.execute("""UPDATE new_listings SET Price =:v1 WHERE Coin = :coin""", {'coin': coin[0], 'v1': coin[2]})
        else:
            c.execute("INSERT INTO new_listings VALUES (?,?,?,?,?,?,?,?)",
                      (coin[0], coin[1], coin[2], coin[3], coin[4], coin[5], coin[6], coin[7],))
    c.execute("DELETE from new_listings WHERE Epoch_Date < :v2", {'v2': time_formatted+360000})

    conn.commit()
    conn.close()

Have tried the below, which first successfully prints table with lisings, however it does not print new table with only 'Trade' = 'True' row(s):

c.execute("SELECT * FROM new_listings")
print("Prints current 'new_listings' table")
for r3 in (c.fetchall()): print("RUNNING SHOW UPDATED new_listings:", r3)
for r2 in (c.fetchall()):
    c.execute("""INSERT INTO trade_schedule SELECT * FROM new_listings WHERE Trade = :t""", {'t':' True'})
c.execute("SELECT * FROM trade_schedule")
print("print content of 'trade_schedule' table")
for r3 in (c.fetchall()): print("RUNNING SHOW UPDATED trade_schedule:", r3)

My final attempt worked, appears to have been a white space " " after 'True ' in the select option that is returned from tkinter which was failing the condition.

While this does allow me to copy the rows from one table to the next using a for loop, I was not able to get it to work using a single sqlite3 syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM