我可以使用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)
请查看此链接:Convert sql result to list python
基本上,你想要类似的东西:
list(cur.fetchall())
相关问题 更多 >
编程相关推荐