连接表的多个列

时间:2014-05-17 11:08:34

标签: python mysql

  • 我正在编写代码,用于从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

1 个答案:

答案 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