使用pythonmysql中的Select查询作为if/else b的参数

2024-10-02 14:20:22 发布

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

我可以使用pythonsqlselect查询的结果作为函数中if/else语句的参数吗?如果我有一个包含一列的数据库,并且想将该列的值附加到Select查询中每一行的列表中……我不能在函数中引用这些查询。例如:

db = MySQLdb.connect(host="localhost", user="root", passwd="****", db="****")
cur = db.cursor()

selectArray1 = []
cur.execute("SELECT * FROM tableName WHERE value = 'x'")
for row in cur.fetchall():
    selectArray1.append(str(row[0]))


selectArray2 = []
cur.execute("SELECT * FROM tableName WHERE value = 'y'")
for row in cur.fetchall():
    selectArray2.append(str(row[0]))

def function(x):
    #----Question-----
    #if I try to print out selectArray1[x] or selectArray2[x], why don't I get
    # a return value?

    #Following conditionals do not work, why not?
    if selectArray1[x] == "some string":
        print "The first array equals the x query"

    if selectArray2[x] == "different string":
        print "The second array equals the y query"

if __name__ == '__main__':
    function(1)
    function(2)

Tags: 函数fromexecutedbifvaluefunctionwhere