如何使python代码中的sql代码可调?

时间:2019-02-18 17:34:47

标签: python sql database

大家好,我想知道是否可以通过输入函数调整python代码中的SQL代码?我目前正在尝试此代码:

import sqlite3

conn = sqlite3.connect('season.sqlite')
cur = conn.cursor()

season_number = input('Enter season id:')

sqlstr = '''SELECT a.home_team AS team_name, a.Points+b.Points as Points
FROM(
SELECT DISTINCT t.name AS home_team, s.name, SUM(CASE
                                         WHEN substr(m.result,1,1) > substr(m.result,-1,1) THEN '3'
                                         WHEN substr(m.result,1,1) < substr(m.result,-1,1) THEN '0'
                                         WHEN substr(m.result,1,1) = substr(m.result,-1,1) THEN '1'
                                         END) AS Points
FROM Match m JOIN Team t
ON t.id=home_team_id
JOIN Season s
ON s.id = m.season_id
WHERE season_id = season_number
GROUP BY t.name
ORDER BY Points DESC) AS a

JOIN(SELECT DISTINCT t.name AS guest_team, s.name, SUM(CASE
                                         WHEN substr(m.result,1,1) < substr(m.result,-1,1) THEN '3'
                                         WHEN substr(m.result,1,1) > substr(m.result,-1,1) THEN '0'
                                         WHEN substr(m.result,1,1) = substr(m.result,-1,1) THEN '1'
                                         END) AS Points
FROM Match m JOIN Team t
ON t.id=guest_team_id
JOIN Season s
ON s.id = m.season_id
WHERE season_id = season_number
GROUP BY t.name
ORDER BY Points DESC) AS b
ON a.home_team=b.guest_team
ORDER BY Points DESC'''

cur.execute(sqlstr)
result = cur.fetchall()
for r in result:
    print(r)

但是很明显,我得到一个错误:

Traceback (most recent call last):
  File "analysis.py", line 38, in <module>
    cur.execute(sqlstr)
sqlite3.OperationalError: no such column: season_number

所以我想知道,是否有一种方法可以将此输入函数包含到SQL代码中,以便我可以按任意方式对数据库进行切片?

我希望我已经很好地解释了这个问题,以便可以理解。我是新手,所以如果您需要更多信息来回答问题,请告诉我。

0 个答案:

没有答案