将数据库中的列与python代码中获得的变量进行比较

2024-05-13 12:49:42 发布

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

我有一个使用Python(mysql.connector)的MySQL数据库。这是我的桌子:

+----+-------+-------+--------+------------+
| id | num1 | num2 | gen | filename   |
+----+-------+-------+--------+------------+
|  1 |    45 |    55 | woman  | vid1.mp4 |
|  2 |    25 |    35 | man    | vid2.mp4 |
|  3 |    45 |    55 | man    | vid3.mp4 |
|  4 |    5 |    15 | woman   | vid4.mp4 |

然后通过查询数据库得到以下列表:

 [(1, 45, 55, 'woman', 'vid1.mp4'), (2, 25, 35, 'man', 'vid2.mp4'),(3, 45, 55, 'man', 'vid3.mp4'),(4, 5, 15, 'woman', 'vid4.mp4')]

我得到代码中的数字和性别,并将其与数据库中输入的num1、num2和性别进行比较。 例如:

if 25<num<35 and gender =='man':
   filename = 'vid2.mp4'

我该如何实现这一点?你知道吗


Tags: 数据库connectormysqlfilenamemp4性别mannum2
1条回答
网友
1楼 · 发布于 2024-05-13 12:49:42

当我有一个像您在这里指定的数据列表时,向其中添加列名是很有用的。你知道吗

data = [(1, 45, 55, 'woman', 'vid1.mp4') ... ] # This comes from DB
col_names = ['id','num1','num2','gen','filename']

接下来,在循环中迭代数据

for row in data:
    # row now contains a single value, for instance (1, 45, 55, 'woman', 'vid1.mp4')

    row_dict = dict(zip(col_names, row)) 
    # row_dict is now a dictionary of {'id':1, 'num1':45 ... }

    if row_dict['num1'] == 25:
        print("%s has an num1 of 25!" % row_dict)

我希望这能让您了解如何迭代您的数据并检测某些值。你知道吗

另一种选择是在循环中使用元组解包

for id, num1, num2, gen, filename in data:
    if num1 == 25:
        print ("wow!")

根据您的编辑:

for id, num1, num2, gen, db_filename in data:
    if 25<num1<35 and gen == 'man':
        filename = db_filename
else:
    print("Oh no, file not found")
    filename = None

相关问题 更多 >