简体   繁体   中英

How do I compare values in a database with variables in SQLite3 with python

Hello there's two things I need help with: Firstly, how would I go about comparing variables with data within a database using SQSLite3? (Line 9) Secondly, how would I combine lines 9 and 11 so when it inserts the data it inserts it on the same line?

import sqlite3

con = sqlite3.connect('Coursework.db')
NumberofS = 59
NumberofMS = 62
X = 'Stationary Waves on a String'
c = con.cursor()

c.execute("INSERT INTO Request (Equipment, Practical_Name) SELECT Equipment, Practical_Name FROM Practicals WHERE Practical_Name = (X) ")

c.execute("INSERT INTO Request (Number_of_Students, Method_Sheets) VALUES(?, ?)", (NumberofS, NumberofMS))

con.commit()

con.close()

Any help would be greatly appreciated

Simply combine both queries in an insert-select with three parameters where numbers parameters run as constants:

sql = (
    "INSERT INTO Request (Equipment, Practical_Name, Number_of_Students, Method_Sheets) "
    "SELECT Equipment, Practical_Name, ? AS Number_of_Students, ? AS Method_Sheets "
    "FROM Practicals "
    "WHERE Practical_Name = ?"
) 

c.execute(sql, [NumberofS, NumberofMS, X])
con.commit()

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