简体   繁体   English

如何获取包含值的Sqlite3列名?

[英]How to get Sqlite3 column names containing a value?

I have a sqlite3 table where it contains 0 and 1. I would like to get the column names where the value is 1. I have tried both description and pragma method and for some reason the result is incorrect. 我有一个sqlite3表,其中包含0和1。我想获取值为1的列名称。我尝试了description和pragma方法,由于某种原因,结果不正确。

Following are my attempts: 以下是我的尝试:

.decription 。去污

allResults = c.execute("SELECT * FROM db_1.hope5 WHERE Vehicle = '{}'".format(veh))
all_columnNames = [tup[0] for tup in allResults.description]
inputs_columnNames = all_columnNames[9:]
inputcheck = [tup[9:] for tup in allResults.fetchall()]
inputSelected = [val for i, val in enumerate(inputs_columnNames) if inputcheck[0][i] == 1]

pragma 语用

c = connection.cursor()
        c.execute("PRAGMA TABLE_INFO(hope5)")
        names = [tup[1] for tup in c.fetchall()]
        names = names[2:]
        result = c.execute("SELECT * FROM hope5 WHERE Vehicle = '{}' ".format(veh))
        result = result.fetchall()
        test = [names[index] for index, val in enumerate(result[0][2:]) if val==1]

Shape of the table 桌子的形状

+----+-----+-----+-----+-----+-----+
| A  |  B  |  C  |  D  |  E  |  F  |
+----+-----+-----+-----+-----+-----+
| 0  |  0  |  1  |  0  | 0   |  1  |
|----|-----|-----|-----|-----|-----|
| 1  |  0  |  0  |  0  | 1   |  0  |
+----+-----+-----+-----+-----+-----+

Based on my above code, the results need to be: 根据我上面的代码,结果需要为:

test = [A,C,E,F]

So the problem was: 所以问题是:

inputSelected = [val for i, val in enumerate(inputs_columnNames) if inputcheck[0][i] == 1]

where the inputcheck[0] should have been j. 其中inputcheck [0]应该是j。 by changing to the following it worked: 通过更改为以下内容,它可以工作:

inputSelected_append = []
for j in range(len(inputcheck)):
    inputSelected = [val for i, val in enumerate(inputs_columnNames) if inputcheck[j][i] == 1]
    inputSelected_append.append(inputSelected)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM