在数据库中查找数据行

2024-04-29 03:37:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些代码方面的基本帮助,我想使用变量self.channels_Index从sqlite3数据库获取数据。你知道吗

每次按下键盘的向下箭头按钮时,我都使用self.channels_Index来定义它。你知道吗

所以当我尝试这个的时候:

programs = list()

#get the programs list
profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', 'source.db'))
con = database.connect(profilePath)
cur = con.cursor()
cur.execute('SELECT channel, title, start_date, stop_date FROM programs WHERE channel=?', [self.channels_Index])
programs = cur.fetchall()
start_pos = 375    # indent for first program
print program

for ind, row in enumerate(programs):
    program = row[1].encode('ascii'), str(row[2]), str(row[3])

我会得到这样的结果:

17:58:26 T:4976  NOTICE: []

我的数据库:

ABC Family
ABC Family
ABC Family
ABC Family
ABC Family
..etc until to 69 rows
CBS
CBS
CBS
CBS
CBS
..etc until to 69 rows
ESPN
ESPN
ESPN
ESPN
ESPN
..etc until to 69 rows
FOX NEWS
FOX NEWS
FOX NEWS
FOX NEWS
FOX NEWS
FOX NEWS
..etc until to 69 rows

我想要实现的是在数据库中找到行,当self.channels_Index显示为7到或任何我想要将它乘以69倍的值时,然后我想要在打印数据列表之前得到69行数据。你知道吗

示例:当self.channels_Index显示为4时,我希望在数据库中找到FOX NEWS行,以69次获得整个数据,然后打印FOX NEWS数据列表。你知道吗

你能帮我怎么用self.channels_Index吗?你知道吗

编辑:当我尝试此操作时:

cur = con.cursor()
cur.execute('SELECT DISTINCT channel FROM programs;')
channel_list = sorted(row[0] for row in cur.fetchall())
cur.execute('SELECT title, start_date, stop_date FROM programs WHERE channel=?;', channel_list[self.channels_Index])
programs = cur.fetchall()

它告诉我错误:ProgrammingError:提供的绑定数量不正确。当前语句使用1,提供了10个。你知道吗


Tags: self数据库indexchannelfamilylistrownews
1条回答
网友
1楼 · 发布于 2024-04-29 03:37:21

看起来您正在使用channels_Index变量来引用ith频道,按字母升序排序。在数据库中,没有保证的排序顺序,因此您必须首先找出ith通道的名称。纯SQL方法是使用显式排序数据的查询;例如,此查询将按字母顺序获得第三个频道:

SELECT DISTINCT channel FROM programs ORDER BY channel ASC LIMIT 1 OFFSET 2;

但是您希望能够浏览不同的频道,OFFSET值不是您可以在查询中参数化的值。更好的解决方案可能是首先获取所有通道名称,然后用Python对它们进行排序:

cur.execute('SELECT DISTINCT channel FROM programs;')
channel_list = sorted(row[0] for row in cur.fetchall())

现在您可以通过将索引应用于channel_list并将结果传递给查询来引用ith频道:

cur.execute('SELECT title, start_date, stop_date FROM programs WHERE channel=?;',
            (channel_list[self.channels_Index],))

你不需要选择channel,因为你已经知道它的值了。无论数据库中有多少行对应于每个通道,这种方法都是有效的。你知道吗

相关问题 更多 >