MySQL
的多个列中获取数据
数据库中。"qwer.txt"
,其中包含LINE1:"I have a car".LINE2:"I have a phone"
tablename
为'adarsh1'
,其中"A1"
列包含汽车
"A2"
包含电话。根据我的编码,它会打印"I have a car"
而不是"I have a car"
和 "I have a phone"
。
那么,我的编码中的问题是什么阻止我打印两行,因为它出现在表格的两列中?
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
# execute SQL select statement
cursor.execute("SELECT A1,A2 FROM adarsh1")
# commit your changes
db.commit()
keywords=[]
#here fetchall() gets all the rows and we append carnames to key words
for i in cursor.fetchall():
keywords.append(i[1])
with open('qwer.txt','r') as file:
for line in file:
for key in keywords:
if key in line:
print line
答案 0 :(得分:1)
您只需在关键字后附加一列。你可能应该追加i [0]和i [1]:
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
# execute SQL select statement
cursor.execute("SELECT A1,A2 FROM adarsh1")
# commit your changes
db.commit()
keywords=[]
#here fetchall() gets all the rows and we append carnames to key words
for i in cursor.fetchall():
keywords.append(i[0])
keywords.append(i[1])
with open('qwer.txt','r') as file:
for line in file:
for key in keywords:
if key in line:
print line