调用mysql并打印匹配文本文件的数据(python)

时间:2014-05-14 03:35:47

标签: php python mysql

我知道要连接到数据库并连接它,我是通过

完成的
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

我有一个文本文件qwer.txt                                                                                              我有表名:vehicle

我需要执行打印与文本文件和数据库匹配的单词的操作。对于小数据库和小文件的操作由此给出,但是如何连接数据库并匹配它们呢?

    mysql_row = "car,bike"
    file_str = "I have a car"

    mysql_elements = mysql_row.split(",")
    file_elements = file_str.split(" ")

    output_array = []

    for m_element in mysql_elements:
        for i in range(len(file_elements)):
            if ((m_element == file_elements[i]) and (i < len(file_elements)-1)):
               output_array.append(file_elements[i])

    print output_array  

输出:车

那么,直接连接数据库和执行匹配操作的文件名需要做哪些更改。

1 个答案:

答案 0 :(得分:0)

cursor = db.cursor()

# execute SQL select statement
cursor.execute("SELECT name FROM Vehicle")

# commit your changes
db.commit()

keywords=[]

这里fetchall()获取所有行,我们将关键词添加到关键词

for i in cursor.fetchall():
    keywords.append(i[0])

with open('qwer.txt','r') as file:

这用于打开文件

    for line in file:
        for key in keywords:
            if key in line:
                print line

对于关键字搜索中的每个单词,该行带来了我们的输出