【问题标题】:calling a mysql and printing data matching text file(python)调用 mysql 并打印数据匹配文本文件(python)
【发布时间】:2014-07-01 22:48:17
【问题描述】:

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

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  

输出:汽车

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

【问题讨论】:

标签: php python mysql


【解决方案1】:
cursor = db.cursor()

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

# commit your changes
db.commit()

keywords=[]

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

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

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

【讨论】:

  • with open('qwer.txt','r') as file: 这是我得到的错误,'r' 是做什么用的?
猜你喜欢
  • 2018-05-07
  • 1970-01-01
  • 2017-10-29
  • 2020-06-12
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
相关资源
最近更新 更多