简体   繁体   中英

How can I use a specified variable in a SELECT SQL statement?

I am creating a program that will allow a user to pick 2 chemical elements from menus and then tell them the result of the reaction between those two. I know my database is working, and I am trying to create two variables that can be changed at any point in the program. This is the code I have so far, using 2 values that I know the correct outcome for:

import sqlite3
conn = sqlite3.connect('Experiment_simulator_database.db')
c = conn.cursor()

firstchoice = 1
secondchoice = 36

sqlcommand = "SELECT Outcome_ID FROM Reactions WHERE Choice_1 = firstchoice AND Choice_2 = secondchoice"
c.execute(sqlcommand)
result = c.fetchone()
print(result)

How can I get firstchoice and secondchoice in the select statement to take on the values I specified above?

You can have placeholders in your sql and bind the values when you call execute

 sqlcommand = "SELECT Outcome_ID FROM Reactions WHERE Choice_1 = ? AND Choice_2 = ?"
 c.execute(sqlcommand, (firstchoice, secondchoice,))

You can pass these variables in parameter where you are using.

firstchoice = 1
secondchoice = 36
sqlcommand = "SELECT Outcome_ID FROM Reactions WHERE Choice_1 = " + firstchoice + "AND Choice_2 = " + secondchoice "
c.execute(sqlcommand, firstchoice, secondchoice)

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