对于我的程序,我需要将两个表连接在一起,我知道该怎么做。但是,我只需要选择某些字段,它们已经存储在python变量中。如何执行sql搜索,只选择包含该变量值的行中的字段?
我正在使用SQLite,目前我所能做的就像是
sql1 = '''SELECT *
FROM Dogs INNER JOIN Owners
ON Dogs.DogID = Owners.DogID
Order By Speed desc;
'''
我需要能够使用变量
答案 0 :(得分:2)
Python手册应该是主要的信息来源。标准库直接提供了一个很好的例子的Sqlite接口。
一个例子只读为:
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()
使用您自己的代码,它会给出:
sql1 = '''SELECT *
FROM Dogs INNER JOIN Owners
ON Dogs.DogID = Owners.DogID
WHERE Dogs.DogID = ?
Order By Speed desc;
'''
c.execute(sql1, dogid)
...
答案 1 :(得分:0)
您可以在SQL数据库中搜索:
import sqlite3
db = sqlite3.connect('db.sq3')
cursor = db.cursor()
to_search = ('value', )
found = cursor.execute('SELECT * FROM table WHERE key=?', to_search).fetchall()
答案 2 :(得分:0)
python中字符串格式的一个小例子:
sql1 = '''SELECT * {0}
FROM {1} INNER JOIN {2}
ON {1}.{3} = {2}.{3}
Order By {4} desc;
'''
print(sql1.format('Spot','Dogs', 'Owners', 'DogID', 'Speed'))