两个问题: 所以我有一个文件名列表,每个文件名都要提供给MYSQL查询。 第一个问题是如何遍历文件列表并将元素(文件名)作为变量传递给MYSQL? 第二个问题是:如何在没有括号和L's形成返回的元组输出的情况下以更优雅的方式打印结果?我的下面的方式有三列,但我想要一种灵活的方式,当我获取更多行时,我不必添加子列表(cleaning1,2 ...)。 任何帮助高度赞赏!!!
MyConnection = MySQLdb.connect( host = "localhost", user = "root", \
passwd = "xxxx", db = "xxxx")
MyCursor = MyConnection.cursor()
**MyList= (File1, File2, File3, File...., File36)
For i in Mylist:
do MYSQL query**
SQL = """SELECT a.column1, a.column2, b.column2 FROM **i in MyList** a, table2 b WHERE
a.column1=b.column1;"""
SQLLen = MyCursor.execute(SQL) # returns the number of records retrieved
AllOut = MyCursor.fetchall()
**List = list(AllOut) # this puts all the TUple information into a list
cleaned = [i[0] for i in List] # this cleans up the Tuple characters)
cleaned1 = [i[1] for i in List] # this cleans up the Tuple characters)
cleaned2 = [i[2] for i in List] # this cleans up the Tuple characters)
NewList=zip(cleaned,cleaned1,cleaned2) # This makes a new List
print NewList[0:10]**
# Close the files
MyCursor.close()
MyConnection.close()
我可以找出保存到文件,但我不知道如何将python变量传递给MYSQL。
答案 0 :(得分:0)
首先将元组转换为列表:使用
MyList = list(MyList)
你将有两个选择: 试试这个:
for tablename in MyList:
c.execute("SELECT a.column1, a.column2, b.column2 FROM %s a, table2 b WHERE a.column1=b.column1", (tablename))
或:
for tablename in MyList:
SQL= "SELECT a.column1, a.column2, b.column2 FROM tablevar a, table2 b WHERE a.column1=b.column1"
SQL = SQL.replace('tablevar', tablename)
c.execute(SQL)
打印结果而不使用您可以使用的括号:
for tablename in MyList:
print tablename